ctime.h

Why is calculating function runtime returning 0 seconds using time.h


I am trying to use time.h to solve for 4 functions runtimes, but my output is returning 0.000000 sec

double timep[4] = {0.0};

clock_t begin, end;

begin = clock();
function1();
end = clock();
timep[0] = (double)(end - begin) / CLOCKS_PER_SEC;

begin = clock();
function2();
end = clock();
timep[1] = (double)(end - begin) / CLOCKS_PER_SEC;

begin = clock();
function3();
end = clock();
timep[2] = (double)(end - begin) / CLOCKS_PER_SEC;

begin = clock();
funtion4();
end = clock();
timep[3] = (double)(end - begin) / CLOCKS_PER_SEC;

Printing the timep array using (%lf) yields

0.000000
0.000000
0.000000
0.000000

Solution

  • It may just be that the functions are relatively fast, combined with the fact the clock often has a minimum resolution (in that it's usually a multiple of some value, supported by your comment that "for some reason the output is rounded, example 1.654000").

    A better way to check may be to time many iterations of the function (assuming no side effects that would affect later runs) and divide the total time by the count, something like:

    #define QUANT 1000
    begin = clock();
    for (int i = 0; i < QUANT; ++i)
        function1();
    end = clock();
    timep[0] = (double)(end - begin) / CLOCKS_PER_SEC / QUANT;
    
    

    This will amortise the errors that may be produced by the afore-mentioned resolution of the clock. A potential error of (for example) +/- 1ms has far less impact on an operation that take 1000ms (the loop of a thousand calls) than one that takes 1ms (a single call).

    The latter could give you any value from 0 to 2ms (+/- 100%), the former 999 to 1001ms (+/- 0.1%).