What is the best, most accurate timer in C ++?

What is the best, most accurate timer in C ++?

+8
source share
4 answers

The answer to this question is platform dependent. The operating system is responsible for tracking time and, therefore, the C ++ language itself does not provide language constructs or built-in functions for this.

However, here are some resources for platform-specific timers:

A cross-platform solution could be boost :: asio :: deadline_timer .

+12
source

In C ++ 11, you can portablely get the timer with the highest resolution with:

 #include <iostream> #include <chrono> #include "chrono_io" int main() { typedef std::chrono::high_resolution_clock Clock; auto t1 = Clock::now(); auto t2 = Clock::now(); std::cout << t2-t1 << '\n'; } 

Output Example:

 74 nanoseconds 

"chrono_io" is an extension to ease I / O problems with these new types and is freely available here .

There is also a <chrono> implementation available in boost (it may still be on the tip of the trunk, not sure if it was released).

+10
source

In windows, it will be a QueryPerformanceCounter , although, seeing that you have not specified any conditions, it is possible to have an external ultra-high resolution timer with a C ++ interface for the driver

+2
source

The C ++ standard does not say much about time. There are several functions inherited from C through the <ctime> header.

The clock function is the only way to get accuracy for the second second, but the accuracy can reach one second (it is determined by the CLOCKS_PER_SEC macro). In addition, it does not measure real time at all, but rather processor time.

The time function measures real time, but (usually) only until the next second.

To measure real time accurate to the second, you need a custom library.

+2
source

All Articles