I have seen many topics about this, even in stackoverflow, for example:
How to measure CPU time and wall time on Linux / Windows?
I want to measure both the processor and the wall time. Although the person who answered the question in the topic that I posted, we recommend using it gettimeofday
to measure time on the wall, I read that it is better to use instead clock_gettime
. So, I wrote the code below (is it normal, does it really measure the wall time, not the processor time? I ask because I found the web page: http://nadeausoftware.com/articles/2012/03/c_c_tip_how_measure_cpu_time_benchmarking#clockgettme , which says that it clock_gettime
measures the time of the processor ...) What is the truth and which one should be used to measure the time on the wall?
Another question about processor time. I found the answer, which is clock
great about this, so I wrote a sample code for it. But this is not what I really want, for my code it shows me 0 seconds of processor time. Is it possible to more accurately measure the processor time (in seconds)? Thanks for any help (at the moment I am only interested in Linux-solutions).
Here is my code:
#include <time.h>
#include <stdio.h> /* printf */
#include <math.h> /* sqrt */
#include <stdlib.h>
int main()
{
int i;
double sum;
struct timespec now, tmstart;
clock_gettime(CLOCK_REALTIME, &tmstart);
for(i=0; i<1024; i++){
sum += log((double)i);
}
clock_gettime(CLOCK_REALTIME, &now);
double seconds = (double)((now.tv_sec+now.tv_nsec*1e-9) - (double)(tmstart.tv_sec+tmstart.tv_nsec*1e-9));
printf("wall time %fs\n", seconds);
double start = (double)clock() /(double) CLOCKS_PER_SEC;
for(i=0; i<1024; i++){
sum += log((double)i);
}
double end = (double)clock() / (double) CLOCKS_PER_SEC;
printf("cpu time %fs\n", end - start);
return 0;
}
Compile it as follows:
gcc test.c -o test -lrt -lm
and he shows me:
wall time 0.000424s
cpu time 0.000000s
I know I can do more iterations, but that is not the point.)
IMPORTANT:
printf("CLOCKS_PER_SEC is %ld\n", CLOCKS_PER_SEC);
shows
CLOCKS_PER_SEC is 1000000