I'm interested in measuring a specific point in time down to the nanosecond using C++ in Windows. Is this possible? If it isn't, is it possible to get the specific time in microseconds at least?. Any library should do, unless I suppose it's possible with managed code. thanks
If you have a threaded application running on a multicore computer
QueryPerformanceCounter can (and will) return different values depending on which core the code is executing on. See this MSDN article. (
rdtsc has the same problem)
This is not just a theoretical problem; we ran into it with our application and had to conclude that the only reliable time source is
timeGetTime which only has ms precision (which fortunately was sufficient in our case). We also tried fixating the thread affinity for our threads to guarantee that each thread always got a consistent value from
QueryPerformanceCounter, this worked but it absolutely killed the performance in the application.
To sum things up there isn't a reliable timer on windows that can be used to time thing with micro second precision (at least not when running on a multicore computer).
Windows has a high-performance counter API.
You need to get the ticks form
QueryPerformanceCounter and divide by the frequency of the processor, provided by
LARGE_INTEGER frequency; if (::QueryPerformanceFrequency(&frequency) == FALSE) throw "foo"; LARGE_INTEGER start; if (::QueryPerformanceCounter(&start) == FALSE) throw "foo"; // Calculation. LARGE_INTEGER end; if (::QueryPerformanceCounter(&end) == FALSE) throw "foo"; double interval = static_cast<double>(end.QuadPart - start.QuadPart) / frequency.QuadPart;
interval should be in seconds.