Question

I'm going to be developing a small dedicated server in C/C++ that will require uptime of forever. I've been looking into some time functions as millisecond timing is required for calculations. I have 2 problems that I'm facing:

  1. Using a 32bit integer to store the number of milliseconds since the operation began will wrap around at about the 49 days mark resetting to zero. I have thought about using 64 bit integers, using gettimeofday to retrieve microseconds but this brings me to the second part.

  2. There doesn't seem to be any standard system calls for getting elapsed milliseconds that are platform independant

What should I do to resolve both these issues?

Was it helpful?

Solution

  1. Use a 64bit integer, presuming that gives you enough time

  2. You are correct; there is no standard. One possibility would be to use the Boost DateTime library, alternately find another or roll your own.

Good Luck!

OTHER TIPS

As has already been said, the first problem you are going to confront is going to obtain a reliable millisecond-precise time.

I admit I am a bit phased by the question though.

I can understand the need for precise timing (millisecond level, even microsecond) but timing a 50days at a millisecond level seems... strange.

You should perhaps review your need first, but it is rare to need more than 6 or 7 significant digits... and I am afraid that you are trying to get a one size fit them all duration object.

Perhaps that you should instead classify your durations:

  • a few minutes at most > use millisecond precision
  • otherwise > use second precision (the famous count since Jan 1st 1970)

Because... what is the sense of 1/10 second at the scale of 2 months ?

Obvious. Use 64-bit integers with platform-specific code to get the number of milliseconds. On Unix including OSX, you want gettimeofday. On Windows, good luck getting a reliable millisecond-granularity time source; the code in the Tcl library to do this is really complex as there are some evil gotchas in the area.

answer to 1: If the "millisecond timing" that you are measuring is under around 20 days, you can subtract the times as unsigned values and check the result as signed value. This should give the right result with wrapping timers (wrapping from 0xffffffff to 0x00000000). If your timing is over 20 days, you need more bits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top