Search code examples
ctimeexecution

How to get execution time of c program?


I am using clock function for my c program to print execution time of current program.I am getting wrong time in output.I want to display time in seconds,milliseconds and microseconds.

#include <stdio.h> 
#include <unistd.h>
#include <time.h> 
int main() 
{ 
    clock_t start = clock(); 
    sleep(3);
    clock_t end = clock(); 
    double time_taken = (double)(end - start)/CLOCKS_PER_SEC; // in seconds 

    printf("time program took %f seconds to execute \n", time_taken); 
    return 0; 
} 


time ./time
time program took 0.081000 seconds to execute
real    0m3.002s
user    0m0.000s
sys     0m0.002s

I expect output around 3 seconds however it display wrong. As you see if I run this program using Linux command time I am getting correct time,I want to display same time using my c program.


Solution

  • Contrary to popular belief, the clock() function retrieves CPU time, not elapsed clock time as the name confusingly may induce people to believe.

    Here is the language from the C Standard:

    7.27.2.1 The clock function

    Synopsis

    #include <time.h>
    clock_t clock(void);
    

    Description

    The clock function determines the processor time used.

    Returns

    The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC. If the processor time used is not available, the function returns the value (clock_t)(−1). If the value cannot be represented, the function returns an unspecified value.

    To retrieve the elapsed time, you should use one of the following:

    • the time() function with a resolution of 1 second
    • the timespec_get() function which may be more precise, but might not be available on all systems
    • the gettimeofday() system call available on linux systems
    • the clock_gettime() function.

    See What specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX? for more information on this subject.

    Here is a modified version using gettimeoday():

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/time.h>
    
    int main() {
        struct timeval start, end;
    
        gettimeofday(&start, NULL);
        sleep(3);
        gettimeofday(&end, NULL);
    
        double time_taken = end.tv_sec + end.tv_usec / 1e6 -
                            start.tv_sec - start.tv_usec / 1e6; // in seconds
    
        printf("time program took %f seconds to execute\n", time_taken);
        return 0;
    }
    

    Output:

    time program took 3.005133 seconds to execute