how to calculate milliseconds using timeval structure?

sam18 picture sam18 · Sep 6, 2013 · Viewed 10.8k times · Source

I want to retrieve values in milliseconds from a variable of type timeval. Below is my attempt:

timeval* time;
long int millis = (time->tv_sec * 1000) + (time->tv_usec / 1000);
printf("Seconds : %ld, Millis : %ld", time->tv_sec, millis);

Output => Seconds : 1378441469, Millis : -243032358

Issue is I am getting millisecond values in minus. What is wrong with this snippets?

Answer

Carl Norum picture Carl Norum · Sep 6, 2013

Assuming you did correctly initialize time, it's because you're overflowing when multiplying time->tv_sec by 1000. In your case, it's 1.4 billion already, and the signed multiplication you're doing ends up overflowing at 2.1 billion or so. Use 64-bit multiplication to get around it:

uint64_t millis = (time->tv_sec * (uint64_t)1000) + (time->tv_usec / 1000);

Make sure to print it out using a reasonable format.