user4793972
user4793972

Reputation: 125

Negative values in time measurement?

I'm trying to measure time in milliseconds:

#include <stdio.h>
#include <time.h>

int main(void)
{
    int i;
    struct timespec start, end;

    for (i = 0; i < 10; i++) {
            clock_gettime(CLOCK_MONOTONIC, &start);
            usleep(500000); // Sleep 500 milliseconds
            clock_gettime(CLOCK_MONOTONIC, &end);

            printf("Elapsed time: %lf \n", (((end.tv_sec - start.tv_sec) / 1.0e3) + ((end.tv_nsec - start.tv_nsec) / 1.0e6)));
    }

    return 0;
}

In the printf function I subtract the seconds and divide by 1000 to convert the result into milliseconds, then I subtract the nano seconds and divide with 1000000 to convert the result into milliseconds, and finally the two results are added.

I think this is the correct way, but for some reason the output contains negative values:

Elapsed time: 500.117421 
Elapsed time: -499.882167 
Elapsed time: 500.193631 
Elapsed time: -499.884990 
Elapsed time: 500.115007 
Elapsed time: -499.877328 
Elapsed time: 500.127219 
Elapsed time: -499.875301 
Elapsed time: 500.124021 
Elapsed time: -499.865300 

What am I doing wrong?

Upvotes: 0

Views: 1618

Answers (1)

alk
alk

Reputation: 70931

To convert seconds to Milli-seconds you need multiply the seconds by 1000.

So this

printf("Elapsed time: %lf \n",
  (((end.tv_sec - start.tv_sec) / 1.0e3) + ((end.tv_nsec - start.tv_nsec) / 1.0e6)));

should be

printf("Elapsed time: %lf \n", 
  (((end.tv_sec - start.tv_sec) * 1.0e3) + ((end.tv_nsec - start.tv_nsec) / 1.0e6)));

Upvotes: 5

Related Questions