Thursday, March 27, 2008

Timing Events in C

It's a pretty standard problem. You want to time how long something takes on your computer, be it calculating the first 10,001 primes, accessing a multidimensional array in different directions, or whatever else you can come up with. The pseudocode for it is pretty simple:

save start_time
do something of interest
save end_time
display (end_time - start_time)

I was reading through some code samples in C today, and found probably the cleanest way to solve this problem so far (allocate.c):

#include time.h
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1)\
{printf("Error calling clock");exit(1);}

#define STOP if ( (stopm = clock()) == -1)\
{printf("Error calling clock");exit(1);}

#define PRINTTIME printf( \
"%6.3f seconds used by the processor.", \


Then in your code:
// Call function of interest

And that's it.
Other than it's clean usage, it also has the advantage of not measuring real time, but processor time. So if this program is pushed out of the CPU by another program, that time won't be added, only the time spent running. The only shortcoming is that this macro can't be nested, but it's hard to believe it'd be that difficult to do.

No comments:

Post a Comment