1
\$\begingroup\$

I needed to make a timer to profile small programs a while back. My use wasn't for a major project or mission critical code or anything even remotely close to that, just for personal learning purposes.

As I reviewed my old timer I found I was using clock which measures cpu time. Now being aware of the difference between wall time and cpu time, I made this timer using clock_gettime and was hoping for help finding any mistakes or possible improvements that could be made. Thanks.

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#define NANO 1000000000
int main(int argc, char *argv[])
{
 struct timespec start;
 struct timespec stop; 
 clock_gettime(CLOCK_REALTIME, &start);
 double start_time = ((float) start.tv_sec) + 
 ((float) start.tv_nsec) / NANO;
 printf("%.4f\n", start_time);
 sleep(3);
 for (int i=1; i < 10000; i++) { 
 for (int j=i; j < 10000; j++) {
 int l = j % i;
 }
 }
 clock_gettime(CLOCK_REALTIME, &stop);
 double stop_time = ((float) stop.tv_sec) + 
 ((float) stop.tv_nsec) / NANO;
 printf("%.4f\n", stop_time - start_time);
 return 0;
}
asked Apr 12, 2016 at 17:17
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

A few things:

  • Why are you mixing float and double? Use one of them and do so consistently.
  • Your for loop doesn't do anything, it has no side effects. So any half-decent compiler will just remove the whole loop when the optimizer is enabled. To prevent this from happening, all variables inside the loop must be declared as volatile.
  • Note that a call to sleep will cause your process to yield its time slice and let the OS context switch and execute code from other processes, before returning to your process. This will cause timing inaccuracies. It is likely that this is the reason why your code seems to work: the loop gets removed and instead you measure some random time when other processes are executing.
answered Apr 13, 2016 at 7:32
\$\endgroup\$
2
  • \$\begingroup\$ On your third point, I was wanting to measure wall time not cpu time. I'm using the timer to run with Project Euler problems, is cpu time the norm when profiling? \$\endgroup\$ Commented Apr 13, 2016 at 15:15
  • 1
    \$\begingroup\$ @tijko Yes, it only makes sense to measure the program's own execution time. But profiling on non-RTOS systems is always a bit of quackery: at best you can to use some "high resolution" timers hopefully available through the API. How to do that is of course system-dependent. \$\endgroup\$ Commented Apr 14, 2016 at 7:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.