0

Possible Duplicate:
C++ Timer function to provide time in nano seconds
High resolution timer with C++ and Linux?

I would like to time a few C functions, and I'm trying to come up with a systematic way of doing so. So far, what I have is the simplest form of timing:

#include <sys/time.h>
struct timeval start_time, end_time;
gettimeofday(&start_time, NULL);
<my function>
gettimeofday(&end_time, NULL);
total_usecs = (end_time.tv_sec-start_time.tv_sec) * 1000000 + 
    (end_time.tv_usec-start_time.tv_usec);
printf ("parfib,%ld,%d\n",(long)res,total_usecs); 

I have also found

timespec time1, time2;
int temp;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
     <my function>
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
cout<<diff(time1,time2).tv_sec<<":"<<diff(time1,time2).tv_nsec<<endl;

But even with std=gnu99 I have not been able to get this to work (I copied the above code from a website, but I did translated into C before compiling :). Regardless, I'm wondering if any of you know of docs or blogs or something that discusses timing functions like I'm trying to do. BEWARE, I'm not after profilers such as gprof or the like, I need this profiler to be hand-made.

Thanks for any tips.

Community
  • 1
  • 1
Dervin Thunk
  • 17,583
  • 26
  • 110
  • 202
  • I guess you need better sampling than the time function? – Santiago V. Nov 15 '11 at 00:02
  • "I need this profiler to be hand-made". If the goal is to *measure*, just wrap a loop around to get all the accuracy you want. If the goal is to effectively *locate speedup opportunities*, measuring ain't gonna do it. *[This does it.](http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024)* – Mike Dunlavey Nov 15 '11 at 01:11

1 Answers1

3

To compile the second example you will need:

gcc -Wall -Wextra -D_POSIX_C_SOURCE=199309L timer.c -lrt

_POSIX_C_SOURCE specifies which POSIX version you're targeting - it needs to be defined before any system header files get included, so doing it via -D is safest. clock_gettime also depends upon linking to librt (-lrt).

Flexo
  • 82,006
  • 22
  • 174
  • 256