Home > Introduction > Runtime calculation

Runtime calculation

As discussed before in introduction, runtime of a function or application is one of the most widely used method of comparison between two algorithms. Even though we have various method of calculating the run time  theoretically, but that gives us only brief idea not the run time.

Before going to actual programming level implimentation of run time lets discuss about general algorithm.

  1. startTime = CurrentTime()
  2. Do_some_process()
  3. endTime = CurrentTime()
  4. TimeDifference = endTime – startTime

So this is a general approach to find the run time by getting the difference between the ending and starting time.

We all know that CPU is capable of making any calculation in micro and nano seconds. Therefore we should approach by calculating the runtime in microseconds or milli seconds.

Now have a look at this basic program

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
int main()
{
	 struct timeval st , et;
	 gettimeofday(&st , NULL);
	 sleep(2);
	 gettimeofday(&et , NULL);
	 printf("\nTotal time taken is : %lu seconds and %lu microseconds\n",(et.tv_sec - st.tv_sec),(et.tv_usec - st.tv_usec));
	 return 0;
}

Try running the above code on your machine. (P.S. It will work only on GCC or G++)
If you are having some trouble then visit http://ideone.com .

Now go ahead and start calculating runtime of your favorite applications 🙂


A General purpose code which can run almost any number of applications.

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

void usage()
{
	printf("Basic usage :\n\ntime.out app1.out \"app2.out < stdin.txt > stdout.txt\" app3.out ... appn.out\n");
}

int main(int argc , char **argv)
{
	struct timeval st , et;
	char str[100];
	unsigned int i=1;
	if(argc == 1)
	{
		usage();
		return -1;
	}
	for(; i < argc ; i++)
	{
		gettimeofday(&st , NULL);
		system(argv[i]);
		gettimeofday(&et , NULL);
		printf("\nTotal time taken by application \"%s\" is : %lu seconds and %lu microseconds\n" , argv[i] , (et.tv_sec - st.tv_sec) , (et.tv_usec - st.tv_usec));

	}
	return 0;
}
Categories: Introduction Tags: ,
  1. No comments yet.
  1. April 7, 2012 at 2:25 PM

Leave a comment