Monthly Archives: October 2014

Precise Elapsed Time Measurement in C Program

This code is the simplest code to measure a program execution time more precisely.

It is using “struct timeval”.

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

double getTimeElapsed(struct timeval end, struct timeval start)
    return (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000000.00;

void main(){
	struct timeval tvalBefore, tvalAfter; 
	gettimeofday(&tvalBefore, NULL);
    // Do something here, this is the simplest program to measure the elapsed time. It is more precise than simple ctimer
	gettimeofday(&tvalAfter, NULL);
	double time_elapsed = getTimeElapsed(tvalAfter, tvalBefore);
	printf("time_elapsed: %lf\n",time_elapsed);

I have referred the below two sites

Good luck ^_^