Microsecond resolution timestamps on Windows

后端 未结 8 542
日久生厌
日久生厌 2020-11-27 16:48

How do I get microsecond resolution timestamps on Windows?

I am loking for something better than QueryPerformanceCounter and QueryPerformanceFrequ

相关标签:
8条回答
  • 2020-11-27 17:29

    QueryPerformanceCounter is the correct solution to this. Contrary to what you and some people answering you wrote, this call gives the correct answer even with multiprocessor systems (unless the system in question is broken), and it handles even changing CPU frequency. On most modern systems it is derived from RDTSC, but handling all those multi-CPU and frequency changing details for you. (It is significantly slower than RDTSC, though).

    See QueryPerformanceCounter

    On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL).

    0 讨论(0)
  • 2020-11-27 17:31

    There's a lot of good information in the answers so far.

    If what you're looking for is a straightforward way to get elapsed time since January 1, 1970 at millisecond or better resolution on Windows XP or later, there's a very simple cross-platform example of this in the CurrentTime.cpp of Apple's OSS release of JavaScriptCore for MacOS 10.7.5 (I can't seem to find it in their 10.8+ releases). The code I'm referring to is in the CurrentTime() function.

    It uses the standard technique of using QueryPerformanceCounter() to calculate elapsed time differences at higher-than-millisecond resolution, and then periodically synchronizing it to the system clock to calculate a timestamp and account for clock drift. In order to get the higher resolution timestamps it requires that you are running Windows XP or later so that calls to QueryPeformanceFrequency() are guaranteed to succeed.

    It doesn't account for context switches throwing things off slightly (as "Implement a Continuously Updating, High-Resolution Time Provider for Windows" and "The Windows Timestamp Project" do), but it does continually re-synchronize. I wouldn't launch a rocket with it, but at around 50 lines of code it's simple to implement and good enough for many purposes.

    Also, if you know that you are guaranteed to be running Windows 8 / Windows Server 2012, you should just use GetSystemTimePreciseAsFileTime(), since it returns the system date and time at the highest possible precision (1 microsecond or better).

    0 讨论(0)
提交回复
热议问题