/** * Example of the use of 3 different ways of timing a function * The function should be fairly long running (say 0.5 sec) to get * reasonably reliable results * * @author gtowell * Created: Sep 2020 * **/ #include #include #define MSEC_MULT 1000000 #include //for gettimeofday #include #include #define COLUM "%10.6f" #ifndef NULL #define NULL (void *) 0 #endif /** * A silly function that just takes a while to complete. * This is the thing to be timed * **/ void work() { //Work to be timed for (int ii=0; ii<20; ii++) { for (int i=0; i<10000000; i++) { int j=i*i; } } // end work } /** * Timing method 1 * Uses the clock function from time.h * Probably the simplest to use, but maybe, arguably the least accurate * **/ void t1() { clock_t start, end; start = clock(); work(); end = clock(); float cpu_time_used = ((float) (end - start)) / CLOCKS_PER_SEC; printf(COLUM, cpu_time_used ); } /** * Timing method 2. * **/ void t2() { struct timeval begin, end; gettimeofday(&begin, NULL); work(); gettimeofday(&end, NULL); float interval=(float)(end.tv_sec*MSEC_MULT+end.tv_usec - begin.tv_sec*MSEC_MULT-begin.tv_usec); printf(COLUM, (interval/MSEC_MULT) ); } /** * Utility function for t4 * pulls the time out of a buffer * **/ double t2d(struct rusage buf) { return (double)(buf.ru_utime.tv_sec + (double) buf.ru_utime.tv_usec / (double) CLOCKS_PER_SEC); } /** * final timing method * Yet another way of doing the same thing * Perhaps the most accurate, perhaps. * **/ void t4() { struct rusage buf; getrusage(RUSAGE_SELF, &buf); double startt=t2d(buf); work(); getrusage(RUSAGE_SELF, &buf); double endt = t2d(buf); printf(COLUM, (endt-startt)); } int main(void) { printf("%10s%10s%10s\n", "T1", "T2", "T4"); for (int i = 0; i < 5; i++) { t1(); t2(); t4(); printf("\n"); } }