Get time difference in microtime in C

By | March 9, 2012

The function gettimeofday can be used to retrieve the total number of seconds and balance microseconds elapsed since EPOCH.

Structure timeval looks like this :

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */

On Linux it can be done like this :

 * Get time difference in microseconds
 * */
#include <stdio.h>
#include <sys/time.h>
double time_diff(struct timeval x , struct timeval y);
int main()
	int i;
	struct timeval before , after;
	gettimeofday(&before , NULL);
	//Time taking task
	for (i=1 ; i <= 100 ; i++)
		printf("%d %d %d n",i, i*i, i*i*i);
	gettimeofday(&after , NULL);

	printf("Total time elapsed : %.0lf us" , time_diff(before , after) ); 
	return 0;

double time_diff(struct timeval x , struct timeval y)
	double x_ms , y_ms , diff;
	x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec;
	y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec;
	diff = (double)y_ms - (double)x_ms;
	return diff;
About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

One Comment

Get time difference in microtime in C
  1. Toby Speight

    That’s really not the best way to do it, as you lose precision by forming two doubles and subtracting them. Much better to do the subtraction of timevals (using the BSD timersub() function if you have it) and then create a double from the result. If you don’t have timersub(), try

    double timediff = (y.tv_sec – x.tv_sec) + 1e-6 * (y.tv_usec – x.tv_usec); /* in seconds */

    And certainly don’t cast x_ms and y_ms to double – a cast is a warning of something that requires greater scrutiny, and over-using is like crying wolf – if it’s all over the place, it loses its shock value.

Leave a Reply

Your email address will not be published. Required fields are marked *