Thursday, February 26, 2009

How to get the elapsed time in millisecs

Finding an elapsed time of a function/API/method will help you to understand its performance and the most of our manager/management will hails u if you give them a nice performance graph/chart of an application :)

My Approach:
You can use gettimeofday at the start and end of your method and then the difference the two will give the elapsed time .. You'll get a structure like the one below:

struct timeval {
time_t tv_sec; /* in secs */
suseconds_t tv_usec; /* in Microseconds */

Code snippet:

int main()
struct timeval start, end;
long mtime, seconds, useconds;

// Get the start time
gettimeofday(&start, NULL);

// Here you go with your method call

// note the end time
gettimeofday(&end, NULL);

seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;

mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

printf("Elapsed time: %ld milliseconds\n", mtime);

return 0;

No comments:

Post a Comment