Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using clock() to measure execution time

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.

like image 332
anshu Avatar asked Oct 05 '12 09:10

anshu


3 Answers

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.

like image 149
Jens Gustedt Avatar answered Oct 22 '22 04:10

Jens Gustedt


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
like image 32
paxdiablo Avatar answered Oct 22 '22 04:10

paxdiablo


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

like image 33
Jeyaram Avatar answered Oct 22 '22 05:10

Jeyaram