User Tools

Site Tools


c:compute-execution-time

This is an old revision of the document!


Compute execution time of a C program

Normal usage:

execution-time.c
#include <sys/time.h>
#include <stdio.h>
 
struct timeval start, end;
 
// Start the timer
gettimeofday(&start, NULL);
 
// Here is the code to be executed
 
// End the timer
gettimeofday(&end, NULL);
 
// Calculating the time difference in seconds and microseconds
long seconds = end.tv_sec - start.tv_sec;
long micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
 
// Convert time to seconds and print
double time_in_seconds = seconds + micros / 1000000.0;
printf("Time elapsed: %ld microseconds (%.6f seconds)\n", micros, time_in_seconds);
c/compute-execution-time.1705446766.txt.gz · Last modified: 2024/01/17 01:12 by odefta