Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring time with a resolution of microseconds in C++?

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?

like image 723
Idov Avatar asked Dec 28 '22 03:12

Idov


2 Answers

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).

like image 83
Steve Townsend Avatar answered Jan 10 '23 17:01

Steve Townsend


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

  • GetSystemTimePreciseAsFileTime: 100ns resolution, synchronized to UTC
  • QueryPerformanceCounter: 100ns resolution, not synchronized to UTC

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

  • MSDN: Acquiring high-resolution time stamps
  • MSDN: QueryPerformanceCounter function
  • MSDN: GetSystemTimePreciseAsFileTime function
  • MSDN: GetSystemTimeAdjustment function (where you can see if Windows is currently running your clock faster or slower in order to catch up to current true UTC time)

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

GetSystemTimeAsFileTime would be useful for something like logging.

like image 31
Ian Boyd Avatar answered Jan 10 '23 17:01

Ian Boyd