3/22/08

Elapsed time in C

Here you will see some ways to calculate elapsed time or execution time or real time of a program, procedure,function,whatever.... This is an example of calculating elapsed time with three different ways in C programming language.
First way is to use the gettimeofday() function. This function works in Linux but not in Windows by default. That's the reason I commented the code which calculate elapsed time with gettimeofday().
Second way is to use the GetTickCount() function from win32 API (windows.h).
Third way is to use the clock() function from time.h.
In the following example the three method are almost the same. Get the time before, get the time after and calculate. I used a function called printmsg which prints a message for PRINT_TIMES times.
This is the code.

#include <stdio.h> //printf()
#include <time.h> //clock()
#include <windows.h> //GetTickCount();

#define PRINT_TIMES 1000

void printmsg(){
int i=0;
for(;i<PRINT_TIMES;i++)
printf("Elapsed time example ");
}

int main(int argc, char *argv[]) {
//struct timeval td_start,td_end;
//float elapsed = 0;
unsigned long tick_start,tick_end;
clock_t clock_start,clock_end;
/*
gettimeofday() doesn't work in windows
but it works very well in Linux
/*
printf("Elapsed time example - gettimeofday()\n");
if(gettimeofday(&td_start,NULL)) {
printf("time failed\n");
exit(1);
}
printmsg();
if(gettimeofday(&td_end,NULL)) {
printf("time failed\n");
exit(1);
}
elapsed = 1000000.0 * (td_end.tv_sec -td_start.tv_sec);
elapsed += (td_end.tv_usec - td_start.tv_usec);
printf("Time elapsed - gettimeofday() is %g
microseconds\n",elapsed);
printf("---------------------------------
------------------\n");
sleep(2);/**/
printf("\n--------------------------------
-------------------\n");
printf("Elapsed time example - GetTickCount()\n\n");
tick_start = GetTickCount();
printmsg();
tick_end = GetTickCount();
printf("\n\n------------------------------
---------------------");
printf("\nTime elapsed with GetTickCount() is
%ld milliseconds\n", tick_end - tick_start);
printf("----------------------------------
-----------------\n\n");
sleep(2);
printf("Elapsed time example - clock()\n\n");
clock_start = clock();
printmsg();
clock_end = clock();
printf("\n\n------------------------------
---------------------\n");
printf("\nTime elapsed with GetTickCount() is
%ld cycles\n",clock_end-clock_start);
exit(0);
}

At this point I would like to remind you that you can use > for output to a file.
For example if you compiled
      gcc elapsedexample.c -o elapsedexample
you can run it like this
      elaspsedexample > result.txt
Now you have the result.txt file and you can open it with any editor you like.
I hope that this example was helpful. If you think there is something wrong please post it. Thank you for posting.
Del.icio.us

No comments:

Related Posts Plugin for WordPress, Blogger...