-
Timing In C++
Hey Folks. Question here. I am writing a program in C++ in linux. I need to time a piece of code. Currently I am using the times function in <sys/times.h>. It gets me the time alright (time differece between start and end of code segment). However, I need a greater accuracy (3 decimal places at least). I want the same degree of accuracy as when I run the "time <progname>" command. For example, for one of my programs the output was:
real 0m0.067s
user 0m0.064s
sys 0m0.004s
when using the "time <programname>. When using times function within my program I get the following: 0.07. If I increase the precision of the output, they are just zeros. Is there any way to have the same degree of accuracy as a "time" command?
-
If you are using Linux, as you say, you should be able to use timespec, which gives you nanosecond precision in timing.
Here is a link: Timespec Reference
In that reference, they say to include os_time.h, but when I used it, I just included time.h, and it worked fine, so you should be able to do it with time.h.
Here is an example on how to use it:
Code:
struct timespec tp;
clock_gettime ( CLOCK_REALTIME, &tp );
Seconds = tp.tv_sec;
NanoSeconds = tp.tv_nsec;