Cross platform millisecond timer lasting more than 49 days? - c++

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:
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.
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?

Use a 64bit integer, presuming that gives you enough time
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!

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.

Related

C++ function that converts time(NULL) to local time

In C++ I'm writing a function that converts time(NULL), which is all the seconds since January 1, 1970 in UTC time, to local time EST in military time format (hours:minutes:seconds). I'm honestly stumped how to mathematically do this so that the program stays accurate as time moves forward.
Also I'm well aware that there is a local time function but I'd like to build this function from the ground up. Does anyone have any advice or tips?
Also I'm well aware that there is a local time function but I'd like to build this function from the ground up. Does anyone have any advice or tips?
Why would you want to do this when there are plenty of free and well-tested packages? As mentioned in the comments, getting daylight savings time correct is non-trivial. Existing packages do just that, and they do it right, based on the IANA tzinfo database.
C options:
std::localtime(). This function uses a global variable; it is not thread safe.
localtime_r(). This is a POSIX function and is not a part of the C++ library. It does not exist on Windows.
localtime_s(). This is an optional C11 function. Even if it exists on your machine, it might not be a part of <ctime>.
C++ options:
Boost Date-Time, https://github.com/boostorg/date_time .
Howard Hinant's date-time module, https://github.com/HowardHinnant/date .
localtime() from glibc should do the job of calculating the date, provided the environment is set to the correct timezone; else use gmtime(). Building a string from the values is a separate job, see strftime() for that.
http://linux.die.net/man/3/localtime
If you want to learn about the algorithms for converting a count of days to a year/month/day triple (and back), here they are, highly optimized, explained in pains-taking detail (don't read while operating heavy machinery):
http://howardhinnant.github.io/date_algorithms.html
You should also know that most (all?) implementations of time() track an approximation of UTC called Unix Time. This count treats leap seconds simply as clock corrections to an imperfect clock. That means you can ignore the effect of leap seconds when converting Unix Time seconds to days (just divide by 86400).
For converting to EST, you have some choices (in order of increasing difficulty and accuracy):
You can ignore daylight savings time and always take the offset as -5 hours.
You can assume the current daylight savings rules, ignoring the fact that they have changed many times in the past, and will likely change again.
You can get the past and present rules from the IANA timezone database,
or your OS's local equivalent.
There are two things which you will need to consider:
1. Leap years
One extra day in a year, that is possible to calculate mathematically.
2. Leap seconds
Seconds inserted or removed as needed (so a minute can have 61 or 59 seconds).
Those are irregular and you will need a lookup table for them. Otherwise your conversion routine will not be correct.
List of them is available for example here: https://en.wikipedia.org/wiki/Leap_second

Is there no equivalent of millis() from Arduino in C++?

I am currently implementing a PID controller for a project I am doing, but I realized I don't know how to ensure a fixed interval for each iteration. I want the PID controller to run at a frequency of 10Hz, but I don't want to use any sleep functions or anything that would otherwise slow down the thread it's running in. I've looked around but I cannot for the life of me find any good topics/functions that simply gives me an accurate measurement of milliseconds. Those that I have found simply uses time_t or clock_t, but time_t only seems to give seconds(?) and clock_t will vary greatly depending on different factors.
Is there any clean and good way to simply see if it's been >= 100 milliseconds since a given point in time in C++? I'm using the Qt5 framework and OpenCV library and the program is running on an ODROID X-2, if that's of any helpful information to anyone.
Thank you for reading, Christian.
I don't know much about the ODROID X-2 platform but if it's at all unixy you may have access to gettimeofday or clock_gettime either one of which would provide a higher resolution clock if available on your hardware.

Difference between clock() and MPI_Wtime()

Quick Question . for MPI implementation of my code ,i am getting a huge difference in both. I know MPI_Wtime is the real time elapsed by each processor and clock() gives a rough idea of the expected time . Do anyone wants to add some assertion ?
The clock function is utterly useless. It measures cpu time, not real time/wall time, and moreover it has the following serious issues:
On most implementations, the resolution is extremely bad, for example, 1/100 of a second. CLOCKS_PER_SECOND is not the resolution, just the scale.
With typical values of CLOCKS_PER_SECOND (Unix standards require it to be 1 million, for example), clock will overflow in a matter of minutes on 32-bit systems. After overflow, it returns -1.
Most historical implementations don't actually return -1 on overflow, as the C standard requires, but instead wrap. As clock_t is usually a signed type, attempting to perform arithmetic with the wrapped values will produce either meaningless results or undefined behavior.
On Windows it does the completely wrong thing and measures elapsed real time, rather than cpu time.
The official definition of clock is that it gives you CPU-time. In Windows, for hysterical historical reasons - it would break some apps if you change it to reflect CPU-time now - on Windows, the time is just elapsed time.
MPI_Wtime gives, as you say, the "current time on this processor", which is quite different. If you do something that sleeps for 1 minute, MPI_Wtime will move 60 seconds forward, where clock (except for Windows) would be pretty much unchanged.

Boost DateTime: time_duration from seconds to multiple days

I know I can use boost::gregorian::date_duration for time intervals in days, and boost::posix_time::time_duration for time intervals, but is there a simple data type I can use for anything from seconds to many days of time interval?
What are the limits (max duration) to boost::posix_time::time_duration ?
From the documentation:
By default the posix_time system uses a 64 bit integer and a 32 bit integer internally to provide nano-second level resolutions -- 96 bits for each time value. As an alternative, a single 64 bit integer can be used to provide a microsecond level resolution. This alternative implementation may provide better performance and more compact memory usage for many applications that do not require nano-second resolutions.
and
The variable BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG, as defined in build/Jamfile, selects between these options. To select the 64 bit integer implementation simply remove this define from the Jamfile.
So as far as you're probably concerned, DevSolar's answer summarizes it nicely at the end.
"POSIX time" usually means "seconds since January 1st, 1970", which is good until about 2037 if you're using a 32-bit value, much longer if you are using 64 bit. So without looking at the exact specs of Boost, I wouldn't worry too much about the limits of boost::posix_time::time_duration.

Portable good precision double timestamp in C++?

Here's what I'd need to do:
double now=getdoubletimestampsomehow();
Where getdoubletimestampsomehow() should be a straight-forward, easy to use function returning a double value representing the number of seconds elapsed from a given date. I'd need it to be quite precise, but I don't really need it to be more precise than a few milliseconds. Portability is quite important, if it isn't possible to directly port it anywhere could you please tell me both an unix and a windows way to do it?
Have you looked at Boost and particularly its Date_Time library ? Here is the seconds since epoch example.
You will be hard-pressed to find something more portable, and of higher resolution.
Portable good precision double timestamp in C++?
There is no portable way to get high-precision timestamp (milliseconds) without using 3rd party libraries. Maximum precision you'll get is 1 second, using time/localtime/gmtime.
If you're fine with 3rd party libraries, use either Boost or Qt 4.
both an unix and a windows way to do it?
GetSystemTime on Windows and gettimeofday on linux.
Please note that if you're planning to use timestamps to determine order of some events, then it might be a bad idea. System clock might have very limited precision (10 milliseconds on windows platform), in which case several operations performed consequently can produce same timestamp. So, to determine order of events you would need "logical timestamps" ("vector clock" is one of examples).
On windows platform, there are highly precise functions that can be used to determine how much time has passed since some point in the past (QueryPerformanceCounter), but they aren't connected to timestamps.
C++11 introduced the <chrono> header containing quite a few portable clocks. The highest resolution clock among them is the std::chrono::high_resolution_clock.
It provides the current time as a std::chrono::time_point object which has a time_since_epoch member. This might contain what you want.
Reference:
Prior to the release of the C++11 standard, there was no standard way in which one could accurately measure the execution time of a piece of code. The programmer was forced to use external libraries like Boost, or routines provided by each operating system.
The C++11 chrono header file provides three standard clocks that could be used for timing one’s code:
system_clock - this is the real-time clock used by the system;
high_resolution_clock - this is a clock with the shortest tick period possible on the current system;
steady_clock - this is a monotonic clock that is guaranteed to never be adjusted.
If you want to measure the time taken by a certain piece of code for execution, you should generally use the steady_clock, which is a monotonic clock that is never adjusted by the system. The other two clocks provided by the chrono header can be occasionally adjusted, so the difference between two consecutive time moments, t0 < t1, is not always positive.
Doubles are not precise - therefore you idea for double now=getdoubletimestampsomehow(); falls down at the first hurdle.
Others have mentioned other possibilities. I would explore those.