3

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?

sam18
  • 631
  • 1
  • 10
  • 24

1 Answers1

6

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.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • Ya you are right. I understand its the case of overflow. but I don't know how to handle it. let me try your suggestion. – sam18 Sep 06 '13 at 05:09