Tag Archives: time

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

http://levicui.blogspot.com/2011/04/calculate-elapsed-time-in-c.html

http://stackoverflow.com/questions/12722904/how-to-use-struct-timeval-to-get-the-execution-time

Good luck ^_^