Measuring time with a resolution of microseconds i

2020-02-07 03:49发布

I'm looking for a way to measure microsecs in C++/Windows.

I read about the "clock" function, but it returns only milliseconds...
Is there a way to do it?

5条回答
Juvenile、少年°
2楼-- · 2020-02-07 03:54

I guess there's nothing wrong with the QuerPerformance* answer already given: the question was for a Windows-specific solution, and this is it. For a cross-platform C++ solution, I guess boost::chrono makes most sense. The Windows implementation uses the QuerPerformance* methods, and you immediately have a Linux and Mac solution too.

查看更多
闹够了就滚
3楼-- · 2020-02-07 04:07

Use QueryPerformanceCounter and QueryPerformanceFrequency for finest grain timing on Windows.

MSDN article on code timing with these APIs here (sample code is in VB - sorry).

查看更多
够拽才男人
4楼-- · 2020-02-07 04:10

http://www.boost.org/doc/libs/1_45_0/doc/html/date_time/posix_time.html

altough

Get the UTC time using a sub second resolution clock. On Unix systems this is implemented using GetTimeOfDay. On most Win32 platforms it is implemented using ftime. Win32 systems often do not achieve microsecond resolution via this API. If higher resolution is critical to your application test your platform to see the achieved resolution.

查看更多
【Aperson】
5楼-- · 2020-02-07 04:14

There are two high-precision (100 ns resolution) clocks available in Windows:

QueryPerformanceCounter is independant of, and isn't synchronized to, any external time reference. It is useful for measuring absolute timespans.

GetSystemTimePreciseAsFileTime is synchronized. If your PC is in the process of speeding up, or slowing down, your clock to bring it gradually into sync with a time server, GetSystemTimePreciseAsFileTime will appropriately be slower or faster than absolute timespans.

The guidance is:

  • if you need UTC synchronized timestamps, for use across multiple systems for example: use GetSystemTimePreciseAsFileTime
  • if you only need absolute timespans: use QueryPerformanceCounter

Bonus Reading

All kernel-level tracing infrastructure in Windows use QueryPerformanceCounter for measuring absolute timespans.

GetSystemTimeAsFileTime would be useful for something like logging.

查看更多
放我归山
6楼-- · 2020-02-07 04:15

More recent implementations can provide microsecond resolution timestamps on windows with high accuracy. The joint use of system filetime and performance counter allows such accuracies see this thread or also this one

One of the recent implementations can be found at the Windows Timestamp Project

查看更多
登录 后发表回答