| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Buried in cloud files? We can help with Spring cleaning!

    Whether you use Dropbox, Drive, G-Suite, OneDrive, Gmail, Slack, Notion, or all of the above, Dokkio will organize your files for you. Try Dokkio (from the makers of PBworks) for free today.

  • Dokkio (from the makers of PBworks) was #2 on Product Hunt! Check out what people are saying by clicking here.

View
 

Timer

Page history last edited by Kenneth Finnegan 13 years, 8 months ago

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);


Sources:

http://www.csce.uark.edu/~aapon/courses/os/examples/

http://kennethfinnegan.blogspot.com/2008/03/timing-events-in-c.html

Comments (0)

You don't have permission to comment on this page.