Thursday, 16 August 2012

Timer

This set of macros is probably most useful when you're playing around with algorithms and need a quick and easy way to figure out how long something will take to run.  You could do this to find bottlenecks, or do benchmarks of one algorithm versus another.  An advantage of these macros is that they only measure CPU time given to this program, so if the program is run on a busy machine, the other programs running won't affect the time measured.

Code:

#include <time.h>
#include <stdlib.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.", ((double)stopm-startm)/CLOCKS_PER_SEC);

Usage:

main() {
     START;
     // Do stuff you want to time
     STOP;
     PRINTTIME;
}


Extensions:

Instead of having PRINTTIME only having a printf in it, change it so it's an fprintf and you can tell it to go whereever you want, be it stderr or even a log file.
#define PRINTTIME(filehandle) fprintf( filehandle, "%6.3f seconds used by the processor.", ((double)stopm-startm)/CLOCKS_PER_SEC);

No comments:

Post a Comment