sam18
sam18

Reputation: 641

how to calculate milliseconds using timeval structure?

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?

Upvotes: 4

Views: 13553

Answers (1)

Carl Norum
Carl Norum

Reputation: 224864

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.

Upvotes: 7

Related Questions