Execution time of C program
CLOCKS_PER_SEC
is a constant which is declared in <time.h>
. To get the CPU time used by a task within a C application, use:
clock_t begin = clock();
/* here, do your time-consuming job */
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
Note that this returns the time as a floating point type. This can be more precise than a second (e.g. you measure 4.52 seconds). Precision depends on the architecture; on modern systems you easily get 10ms or lower, but on older Windows machines (from the Win98 era) it was closer to 60ms.
clock()
is standard C; it works "everywhere". There are system-specific functions, such as getrusage()
on Unix-like systems.
Java's System.currentTimeMillis()
does not measure the same thing. It is a "wall clock": it can help you measure how much time it took for the program to execute, but it does not tell you how much CPU time was used. On a multitasking systems (i.e. all of them), these can be widely different.
If you are using the Unix shell for running, you can use the time command.
doing
$ time ./a.out
assuming a.out as the executable will give u the time taken to run this
In plain vanilla C:
#include <time.h>
#include <stdio.h>
int main()
{
clock_t tic = clock();
my_expensive_function_which_can_spawn_threads();
clock_t toc = clock();
printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
return 0;
}
You functionally want this:
#include <sys/time.h>
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
/* stuff to do! */
gettimeofday(&tv2, NULL);
printf ("Total time = %f seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
Note that this measures in microseconds, not just seconds.
Most of the simple programs have computation time in milli-seconds. So, i suppose, you will find this useful.
#include <time.h>
#include <stdio.h>
int main(){
clock_t start = clock();
// Execuatable code
clock_t stop = clock();
double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
printf("Time elapsed in ms: %f", elapsed);
}
If you want to compute the runtime of the entire program and you are on a Unix system, run your program using the time command like this time ./a.out