Calculate time to execute a function

Csi picture Csi · May 8, 2015 · Viewed 8.4k times · Source

I need to calculate the execution time of a function.

Currently, I use time.h

At the beginning of the function:

time_t tbegin,tend;
double texec=0.000;
time(&tbegin);

Before the return:

 time(&tend);
 texec = difftime(tend,tbegin);

It works fine but give me a result in texec as a integer.

How can I have my execution time in milliseconds ?

Answer

udit043 picture udit043 · May 8, 2015

Most of the simple programs have computation time in milliseconds. So, I suppose, you will find this useful.

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

int main() {
    clock_t start = clock();
    // Executable code
    clock_t stop = clock();

    double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
    printf("Time elapsed in ms: %f\n", elapsed);
}

If you want to compute the run-time of the entire program and you are on a Unix system, run your program using the time command, like this: time ./a.out