A simple code to calculate runtime

The code below gives the time difference between the execution of two code snippets. It uses the system’s microsecond clock.

#include <stdio.h>
#include <sys/time.h>
void main()
struct timeval tv;         //this structure is defined in the system, and contains the variables tv_sec,
//which records seconds, and tv_usec, which records microseconds.
struct timeval tv1;

int i;
gettimeofday(&tv, 0); //gettimeofday gets the required values into tv_sec and tv_usec

//embed your code here. I have simply put in a for loop
{ i++; }

gettimeofday(&tv1, 0);
long long elapsed = (tv1.tv_sec-tv.tv_sec)*1000000 + tv1.tv_usec-tv.tv_usec;  //notice the long long
//datatype  – it is twice the size of long
printf(“time elapsed = %lld microseconds\n”,elapsed);

You can find the complete specs of the microsecond clock , including estimated error and accuracy here: http://www.gnu.org/software/libc/manual/html_node/High-Accuracy-Clock.html


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: