I am trying to use time() to measure various points of my program.
What I don't understand is why the values in the before and after are the same? I understand this is not the best way to profile my program, I just want to see how long something take.
printf("**MyProgram::before time= %ld\n", time(NULL));
doSomthing();
doSomthingLong();
printf("**MyProgram::after time= %ld\n", time(NULL));
I have tried:
struct timeval diff, startTV, endTV;
gettimeofday(&startTV, NULL);
doSomething();
doSomethingLong();
gettimeofday(&endTV, NULL);
timersub(&endTV, &startTV, &diff);
printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);
How do I read a result of **time taken = 0 26339
? Does that mean 26,339 nanoseconds = 26.3 msec?
What about **time taken = 4 45025
, does that mean 4 seconds and 25 msec?
C++ std::chrono has a clear benefit of being cross-platform. However, it also introduces a significant overhead compared to POSIX clock_gettime(). On my Linux box all
std::chrono::xxx_clock::now()
flavors perform roughly the same:Though POSIX
clock_gettime(CLOCK_MONOTONIC, &time)
should be same assteady_clock::now()
but it is more than x3 times faster!Here is my test, for completeness.
And this is the output I get when compiled with gcc7.2 -O3:
time(NULL)
returns the number of seconds elapsed since 01/01/1970 at 00:00 (the Epoch). So the difference between the two values is the number of seconds your processing took.You can get finer results with
getttimeofday()
, which return the current time in seconds, astime()
does and also in microseconds.I usually use the following:
It's the same as @nikos-athanasiou proposed except that I avoid using of a non-steady clock and use floating number of seconds as a duration.
On linux, clock_gettime() is one of the good choices. You must link real time library(-lrt).
The values printed by your second program are seconds, and microseconds.