Using clock() to measure execution time

喜欢而已 提交于 2019-12-18 06:46:28

问题


I am running a C program using GCC and a proprietary DSP cross-compiler to simulate some functioality. I am using the following code to measure the execution time of particular part of my program:

clock_t start,end;
printf("DECODING DATA:\n");
start=clock();
conv3_dec(encoded, decoded,3*length,0);
end=clock();
duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("DECODING TIME = %f\n",duration);

where conv3_dec() is a function defined in my program and I want to find the run-time of this function.

Now the thing is when my program runs, the conv3_dec() functions runs for almost 2 hours but the output from the printf("DECODING TIME = %f\n",duration) says that the execution of the function finished in just half a second (DECODING TIME = 0.455443) . This is very confusing for me.

I have used the clock_t technique to measure the runtimes of programs previously but the difference has never been so huge. Is this being caused by the cross-compiler. Just as a side note, the simulator simulates a DSP processor running at just 500MHz, so is the difference in the clock speeds of the DSP processor and my CPU causing the error is measuring the CLOCKS_PER_SEC.


回答1:


For durations like two hours, I wouldn't be too concerned about clock(), it's far more useful for measuring sub-second durations.

Just use time() if you want the actual elapsed time, something like (dummy stuff supplied for what was missing):

#include <stdio.h>
#include <time.h>

// Dummy stuff starts here
#include <unistd.h>
#define encoded 0
#define decoded 0
#define length 0
static void conv3_dec (int a, int b, int c, int d) {
    sleep (20);
}
// Dummy stuff ends here

int main (void) {
    time_t start, end, duration;
    puts ("DECODING DATA:");
    start = time (0);
    conv3_dec (encoded, decoded, 3 * length, 0);
    end = time (0);
    duration = end - start;
    printf ("DECODING TIME = %d\n", duration);
    return 0;
}

which generates:

DECODING DATA:
DECODING TIME = 20



回答2:


clock measures the cpu time and not the wallclock time. Since you are not running the majority of your code on the cpu, this is not the right tool.




回答3:


gettimeofday() function also can be considered.


The gettimeofday() function shall obtain the current time, expressed as seconds and microseconds since the Epoch, and store it in the timeval structure pointed to by tp. The resolution of the system clock is unspecified.


Calculating elapsed time in a C program in milliseconds

http://www.ccplusplus.com/2011/11/gettimeofday-example.html



来源:https://stackoverflow.com/questions/12743063/using-clock-to-measure-execution-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!