Is there a way in C++ on windows to measure time in nanoseconds?
All i can find are linux solutions.
Use the QueryPerformanceFrequency
function to see what speed the QueryPerformanceCounter runs at. I think it might be in the nanosecond range.
Look into QueryPerformanceCounter on windows.
When timing code to identify performance bottlenecks, you want to use the highest resolution timer the system has to offer. This article describes how to use the QueryPerformanceCounter function to time application code
http://support.microsoft.com/kb/172338
If you can run your own assembly, you could read the CPU's cycle counter and divide a cycle difference it by the CPU's clock rate:
static inline uint64_t get_cycles()
{
uint64_t t;
__asm__ __volatile__ ("rdtsc" : "=A"(t));
return t;
}
rdtsc
has been available since P6-family CPUs, possibly even the original Pentium. It can be restricted to kernel mode, but i don't know if Windows does that - cHao 2012-04-04 22:03
long long ticks()
{
__asm {rdtsc};
}
And if by newer CPUs you mean Pentium, yeah, then it's only available on "newer" CPUs. Personally, though, it's been a while since I coded for the 486 and earlier - Andreas Magnusson 2012-04-04 22:21
Use Windows7 and the Hardware Counter Profiling API http://msdn.microsoft.com/en-us/library/windows/desktop/dd796395(v=vs.85).aspx
Both rdtsc and QueryPerformanceCounter/QueryPerformanceFrequency are not accurate enough because of the large overhead, interrupts and task switches.
[EDIT]: Sorry mixed up the link for PerformanceCounter with Hardware Counters. Sorry have used it only once and this was a quick answer.
rdtsc
and QueryPerformanceCounter
(et al) (most likely QPC
is implemented in terms of rdtsc
) isn't in the overhead, it's in the synchronization across CPU-cores. Each core has its own time stamp counter and there are no syncronization between them - Andreas Magnusson 2012-04-04 22:38
rdtsc
(or QPC
). It's a tool and as most tools it has pros and cons. It's up to the reader to weigh them and make a judgement. Secondly, calling rdtsc
twice in a row takes 24 cycles (and that includes the necessary instructions to save the value from the first call), not so much of an overhead IMHO. Thirdly, last I checked W2K was released in 2000, you must be thinking of Windows NT4 - Andreas Magnusson 2012-04-04 23:14