Take the 2-minute tour ×

I am trying to measure how long a function takes.

I have a little issue: although I am trying to be precise, and use floating points, every time I print my code using %lf I get one of two answers: 1.000... or 0.000.... This leads me to wonder if my code is correct:

#define BILLION  1000000000L;

// Calculate time taken by a request
struct timespec requestStart, requestEnd;
clock_gettime(CLOCK_REALTIME, &requestStart);
clock_gettime(CLOCK_REALTIME, &requestEnd);

// Calculate time it took
double accum = ( requestEnd.tv_sec - requestStart.tv_sec )
  + ( requestEnd.tv_nsec - requestStart.tv_nsec )
printf( "%lf\n", accum );

Most of this code has not been made by me. This example page had code illustrating the use of clock_gettime: http://www.users.pjwstk.edu.pl/~jms/qnx/help/watcom/clibref/qnx/clock_gettime.html

Could anyone please let me know what is incorrect, or why I am only getting integer values please?

Thank you very much,


share|improve this question
No, no, no: don't give names to numbers. Use the function they serve instead: #define CLOCK_PRECISION 1000000000L /* one billion */ –  pmg Oct 15 '10 at 23:51
@pmg: Pedantry tangent: I'd argue that a name such as CLOCK_PRECISION would only be necessary if the units were not clear from the variable name. In the case above, it's clear from the name tv_nsec that we're in nanoseconds. So NANOSECONDS_PER_SECOND might be appropriate, but that's really not a great deal different to simply BILLION. –  Oliver Charlesworth Oct 15 '10 at 23:57

2 Answers 2

up vote 7 down vote accepted

Dividing an integer by an integer yields an integer. Try this:

#define BILLION 1E9

And don't use a semicolon at the end of the line. #define is a preprocessor directive, not a statement, and including the semicolon resulted in BILLION being defined as 1000000000L;, which would break if you tried to use it in most contexts. You got lucky because you used it at the very end of an expression and outside any parentheses.

share|improve this answer
Thanks a lot for your help. And thanks for letting me know about the semicolon, that is something I forgot. Thank you very much! –  Jary Oct 15 '10 at 23:42

( requestEnd.tv_nsec - requestStart.tv_nsec ) is of integer type, and is always less than BILLION, so the result of dividing one by the other in integer arithmetic will always be 0. You need to cast the result of the subtraction to e.g. double before doing the divide.

share|improve this answer

Your Answer


