How to get accurate exact C ++ time

I am running my code on Ubuntu and I need to get the elapsed time about the function in my program. I need a very accurate time, for example, nano seconds or at least microseconds.

I read about chrono.h , but it uses system time, and I prefer to use processor time.

Is there a way to do this and have this granularity (nano seconds)?

+6
source share
3 answers

The achievable accuracy of the watch is one of the properties of various hardware / OS that still runs in almost every language, and, frankly, in the same situation, I find my own abstraction, which is good enough in your case is often the only choice.

Speaking of which, I would avoid STL for high precision time. Since it is a library standard without any true implementation, it must create an abstraction that implies one of:

  • use the lowest common denominator
  • hardware / OS information using platform-specific behavior

In the second case, you essentially return to where you started if you want to have consistent behavior. If you can afford a possible loss of accuracy or deviation of a standard watch, then be sure to use it. The watch is hard and thin.

If you know the target environment, you can select the appropriate hours along the oldschool path ( #ifdef PLATFORM_ID... ), for example. clock_gettime() , QPC ) and implement the exact abstraction can be obtained. Of course, you are limited to the same choice as STL, but by reducing the set of platforms, you can usually improve the lcd requirements.

If you need a more theoretical way to convince yourself of this argument, you can consider a set of watches with maximum accuracy and a sequence of calls to the current time. In order for the clock to move evenly in a uniform manner, if two accesses are faster than the maximum accuracy of one measure, but slower than the maximum accuracy of other watches, you should get a different behavior. If, on the other hand, you guarantee that two accesses are at least the maximum accuracy of the slowest hours, and the behavior is the same. Now, of course, the real clock is not moving evenly (clock drift), and also not in block steps.

+1
source

std::chrono has high_resolution_clock , although please keep in mind that precision is limited by the processor.

If you want to use the function catalog from libc, you can use gettimeofday , but there is still no guarantee that it will be nanosecond. (this is only microsecond accuracy)

+4
source

As long as there is a standards function that should return processor time ( std::clock ), there really is no portable way to do this.

On POSIX systems (which Linux is trying to do), std::clock should do everything right. Just don't expect it to work on platforms other than POSIX if you ever want to make your application portable.

The values ​​returned by std::clock are also approximate, and accuracy and resolution are system dependent.

+1
source

All Articles