简体   繁体   中英

Measuring time in C++

This is my c++ code.

double start_time = time(NULL);
double start_clock = clock();

#pragma omp parallel for private(i) 
for(i=0;i<max_i;i++)
      PROCESS(i);

double end_time = time(NULL);
double end_clock = clock();

printf("%lf second(s)\n", end_time-start_time);
printf("%lf second(s)\n", (end_clock-start_clock)/CLOCKS_PER_SEC);

and this is the output.

took 2.000000 second(s)
took 11.410000 second(s)

Does anyone know why these are not consistent? Is there any other way of measuring this? BTW, 2 seconds seems more reasonable based on the time I'm seeing here.

The clock() function returns the amount of CPU time used by your process since it started, not the absolute time according to a real-time clock.

In another comment you said that CODE_BLOCK is a parallel loop - which means in your case, it used the equivalent of 11.41 seconds of CPU time in 2 seconds of real ("wall clock") time. Evidently you're using the power of about 6 CPUs in parallel.

This might help:

int main() {
    double start_time = time(NULL);
    double start_clock = clock();

    sleep(10);

    double end_time = time(NULL);
    double end_clock = clock();

    printf("%lf second(s)\n", end_time-start_time);
    printf("%lf second(s)\n", (end_clock-start_clock)/CLOCKS_PER_SEC);
}

The output of this is:

10.000000 second(s)
0.000070 second(s)

So, if you're calling out to the kernel in any manner, or hopping off the processor, that will only show up in one of the two timers.

From the note that said you were using OpenMP: What you're likely also seeing is a multiplier effect as well. If your openMP thread is using 8 cores, the second timer is going to count 8 times as much as the first one.

You didn't post what was in your code-block, but in general the time will vary since you're measuring the absolute time in clock ticks that your program has been running since the start of the program as well as measuring the actual amount of CPU-time your program consumed. Those are two drastically different things.

Also the values returned from clock() are not floating point values; they should be clock_t type values, which are an integral type. The same is true for time() which returns a time_t type. Thus there is no need to assign them to floating point types until you perform some type of division and you want a floating point value as the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM