I just started programming C++ in Linux, can anyone recommend a good way for measurement of code elapsed time, ideally to nanoseconds precision, but milli-seconds will do as well.
And also a fast printing method, I am using std::cout at the moment, but I feel it’s kind of slow.
Thanks.
To get a time in nanoseconds, use
clock_gettime(). To measure an elapsed time taken by the code,CLOCK_MONOTONIC_RAWclock type must be used. Using other clock types is not really a solution because they are subject to NTP adjustments.As for the printing part – define slow. A “general” code to convert built-in data types into ASCII strings is always slow. There is also a buffering going on (which is good in most cases). If you can make some good assumptions about your data, you can always throw in your own conversion to ASCII which will beat a general-purpose solutions, and make it faster.
EDIT:
See also an example of using
clock_gettime()function and OS X specificmach_absolute_time()functions here: