Visual C++ Stopwatch
See the question and my original answer on StackOverflowFor what it's worth, here is a Windows implementation (quite similar to .NET):
class Stopwatch
{
LARGE_INTEGER _startTime;
LARGE_INTEGER _frequency;
public:
Stopwatch(bool start = false) :_startTime({ 0 })
{
QueryPerformanceFrequency(&_frequency);
if (start)
{
Start();
}
}
LONGLONG GetStartTime() { return _startTime.QuadPart; }
bool IsStarted() { return _startTime.QuadPart; }
bool IsStopped() { return !IsStarted(); }
void Start()
{
QueryPerformanceCounter(&_startTime);
}
void Stop()
{
ZeroMemory(&_startTime, sizeof(LARGE_INTEGER));
}
static LONGLONG GetFrequency()
{
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
return li.QuadPart;
}
static LONGLONG GetTicks()
{
LARGE_INTEGER endingTime;
QueryPerformanceCounter(&endingTime);
return endingTime.QuadPart;
}
LONGLONG GetElapsedTicks(bool restart = false)
{
LARGE_INTEGER endingTime;
QueryPerformanceCounter(&endingTime);
auto qp = endingTime.QuadPart - _startTime.QuadPart;
if (restart)
{
Start();
}
return qp;
}
LONGLONG GetElapsed100NanoSeconds(bool restart = false)
{
LARGE_INTEGER endingTime;
QueryPerformanceCounter(&endingTime);
LARGE_INTEGER elapsed100NanoSeconds{};
elapsed100NanoSeconds.QuadPart = endingTime.QuadPart - _startTime.QuadPart;
elapsed100NanoSeconds.QuadPart *= 10000000;
elapsed100NanoSeconds.QuadPart /= _frequency.QuadPart;
if (restart)
{
Start();
}
return elapsed100NanoSeconds.QuadPart;
}
LONGLONG GetElapsedMicroseconds(bool restart = false)
{
LARGE_INTEGER endingTime;
QueryPerformanceCounter(&endingTime);
LARGE_INTEGER elapsedMicroSeconds{};
elapsedMicroSeconds.QuadPart = endingTime.QuadPart - _startTime.QuadPart;
elapsedMicroSeconds.QuadPart *= 1000000;
elapsedMicroSeconds.QuadPart /= _frequency.QuadPart;
if (restart)
{
Start();
}
return elapsedMicroSeconds.QuadPart;
}
LONGLONG GetElapsedMilliseconds(bool restart = false)
{
LARGE_INTEGER endingTime;
QueryPerformanceCounter(&endingTime);
LARGE_INTEGER elapsedMilliSeconds{};
elapsedMilliSeconds.QuadPart = endingTime.QuadPart - _startTime.QuadPart;
elapsedMilliSeconds.QuadPart *= 1000;
elapsedMilliSeconds.QuadPart /= _frequency.QuadPart;
if (restart)
{
Start();
}
return elapsedMilliSeconds.QuadPart;
}
LONGLONG GetElapsedSeconds(bool restart = false)
{
LARGE_INTEGER endingTime;
QueryPerformanceCounter(&endingTime);
LARGE_INTEGER elapsedSeconds{};
elapsedSeconds.QuadPart = endingTime.QuadPart - _startTime.QuadPart;
elapsedSeconds.QuadPart /= _frequency.QuadPart;
if (restart)
{
Start();
}
return elapsedSeconds.QuadPart;
}
};