简体   繁体   中英

Measuring time taken by a function: clock_gettime

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);
function_call();
clock_gettime(CLOCK_REALTIME, &requestEnd);

// Calculate time it took
double accum = ( requestEnd.tv_sec - requestStart.tv_sec )
  + ( requestEnd.tv_nsec - requestStart.tv_nsec )
  / BILLION;
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 :

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

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.

( 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 eg double before doing the divide.

请注意, (requestEnd.tv_nsec - requestStart.tv_nsec) 可以为负数,在这种情况下,您需要从 tv_sec 差异中减去 1 秒,并将 tv_nsec 差异增加 10 亿。

I know the question was posted long ago, but I still don't see the answer which would suggest you to "convert" elapsed time into nanoseconds (or milliseconds) and not into seconds as in your code sample.

The sample code fragment to illustrate the idea:

long long accum = ( requestEnd.tv_nsec - requestStart.tv_nsec )
 + ( requestEnd.tv_sec - requestStart.tv_sec ) * BILLION;

This way you can avoid floating point arithmetic, which may be heavy for some platforms...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM