fully separated date with milliseconds from std::chrono::system_clock - c++

My current pattern (for unix) is to call gettimeofday, cast the tv_sec field to a time_t, pass that through localtime, and combine the results with tv_usec. That gives me a full date (year, month, day, hour, minute, second, nanoseconds).
I'm trying to update my code to C++11 for portability and general good practice. I'm able to do the following:
auto currentTime = std::chrono::system_clock::now( );
const time_t time = std::chrono::system_clock::to_time_t( currentTime );
const tm *values = localtime( &time );
// read values->tm_year, etc.
But I'm stuck on the milliseconds/nanoseconds. For one thing, to_time_t claims that rounding is implementation defined (!) so I don't know if a final reading of 22.6 seconds should actually be 21.6, and for another I don't know how to get the number of milliseconds since the previous second (are seconds guaranteed by the standard to be regular? i.e. could I get the total milliseconds since the epoch and just modulo it? Even if that is OK it feels ugly).
How should I get the current date from std::chrono::system_clock with milliseconds?

I realised that I can use from_time_t to get a "rounded" value, and check which type of rounding occurred. This also doesn't rely on every second being exactly 1000 milliseconds, and works with out-of-the-box C++11:
const auto currentTime = std::chrono::system_clock::now( );
time_t time = std::chrono::system_clock::to_time_t( currentTime );
auto currentTimeRounded = std::chrono::system_clock::from_time_t( time );
if( currentTimeRounded > currentTime ) {
-- time;
currentTimeRounded -= std::chrono::seconds( 1 );
}
const tm *values = localtime( &time );
int year = values->tm_year + 1900;
// etc.
int milliseconds = std::chrono::duration_cast<std::chrono::duration<int,std::milli> >( currentTime - currentTimeRounded ).count( );

Using this free, open-source library you can get the local time with millisecond precision like this:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << make_zoned(current_zone(),
floor<milliseconds>(system_clock::now())) << '\n';
}
This just output for me:
2016-09-06 12:35:09.102 EDT
make_zoned is a factory function that creates a zoned_time<milliseconds>. The factory function deduces the desired precision for you. A zoned_time is a pairing of a time_zone and a local_time. You can get the local time out with:
local_time<milliseconds> lt = zt.get_local_time();
local_time is a chrono::time_point. You can break this down into date and time field types if you want like this:
auto zt = make_zoned(current_zone(), floor<milliseconds>(system_clock::now()));
auto lt = zt.get_local_time();
local_days ld = floor<days>(lt); // local time truncated to days
year_month_day ymd{ld}; // {year, month, day}
time_of_day<milliseconds> time{lt - ld}; // {hours, minutes, seconds, milliseconds}
// auto time = make_time(lt - ld); // another way to create time_of_day
auto y = ymd.year(); // 2016_y
auto m = ymd.month(); // sep
auto d = ymd.day(); // 6_d
auto h = time.hours(); // 12h
auto min = time.minutes(); // 35min
auto s = time.seconds(); // 9s
auto ms = time.subseconds(); // 102ms

Instead of using to_time_t which rounds off you can instead do like this
auto tp = std::system_clock::now();
auto s = std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());
auto t = (time_t)(s.count());
That way you get the seconds without the round-off. It is more effective than checking difference between to_time_t and from_time_t.

I read the standard like this:
It is implementation defined whether the value is rounder or truncated, but naturally the rounding or truncation only occurs on the most detailed part of the resulting time_t. That is: the combined information you get from time_t is never more wrong than 0.5 of its granularity.
If time_t on your system only supported seconds, you would be right that there could be 0.5 seconds systematic uncertainty (unless you find out how things were implemented).
tv_usec is not standard C++, but an accessor of time_t on posix. To conclude, you should not expect any rounding effects bigger than half of the smallest time value difference your system supports, so certainly not more than 0.5 micro seconds.
The most straight forward way is to use boost ptime. It has methods such as fractional_seconds()
http://www.boost.org/doc/libs/1_53_0/doc/html/date_time/posix_time.html#date_time.posix_time.ptime_class
For interop with std::chrono, you can convert as described here: https://stackoverflow.com/a/4918873/1149664
Or, have a look at this question: How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

Related

Converting time to local zone time: issue with hh_ss_mm template args (C++ 14)

I'm using C++14 and the famous Date library by #HowardHinnant
I'm trying to convert a GMT (UTC) time to the time inside of some timezone. I need to have it in the tm struct.
All seems good except I can't seem to properly construct the hms object. My template arguments mismatch.
tm Time_hrv::gmtTM_to_timezoneTM(const tm& timeTM_gmt, const std::string& wanted_timezoneStr){
assert(timeTM_gmt.tm_year < 1000);// the year of tm should be relative to 1900. For example, 2020 should be 120.
assert(timeTM_gmt.tm_mon < 12);// [0,11]
assert(timeTM_gmt.tm_mday > 0 && timeTM_gmt.tm_mday<=31);// [0,31]
time_t timeT_gmt = Time_hrv::timeTM_to_timeT(timeTM_gmt);
auto chronoTime_gmt = std::chrono::system_clock::from_time_t(timeT_gmt);
const date::time_zone* wanted_timeZone = timeZone_fromString(wanted_timezoneStr);
//https://stackoverflow.com/a/70759851/9007125
//NOTICE: local_time isn't necessarily the computer's local time.
//It is a local time that has not yet been associated with a time zone.
//When you construct a zoned_time, you associate a local time with a time zone.
auto lt = wanted_timeZone->to_local(chronoTime_gmt);
auto localDay = date::floor<date::days>(lt);
date::year_month_day ymd{ localDay };
date::hh_mm_ss<std::chrono::milliseconds> hms{ lt - localDay }; //<--- error here
tm result = {0};
result.tm_year = int{ymd.year()} - 1900;
result.tm_mon = unsigned{ymd.month()} -1;
result.tm_mday = unsigned{ymd.day()};
result.tm_hour = (int)hms.hours().count();
result.tm_min = (int)hms.minutes().count();
result.tm_sec = (int)hms.seconds().count();
return result;
}
This is chrono giving you a bad error message for a real problem: You are attempting to silently truncate a fine precision expression (lt - localDay) to a coarser precision (milliseconds).
The expression lt - localDay is a type that has precision of system_clock::duration, which is somewhere between microseconds and nanoseconds depending on your platform. This is true, even though the source (and thus the value) of chronoTime_gmt only has precision of seconds at run time.
The easiest fix is to recognize that anything coming from a tm is at best seconds precision by truncating to seconds precision early:
auto chronoTime_gmt = date::floor<std::chrono::seconds>
(std::chrono::system_clock::from_time_t(timeT_gmt));
Now chronoTime_gmt has type time_point<system_clock, seconds>. And therefore the later expression lt - localDay will also have type seconds, which will implicitly convert to the milliseconds precision of your hh_mm_ss.
A suggestion is to also use seconds for the template parameter of your hh_mm_ss since the milliseconds precision goes unused. This won't change correctness or performance of your code, but the reader of your code will no longer spend time wondering why you chose milliseconds and then didn't use it.

Validate timestamp for a particular duration in C++

I want to see whether my data is 120 second old by looking at the timestamp of the data so I have below code:
uint64_t now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
bool is_old = (120 * 1000 < (now - data_holder->getTimestamp()));
In the above code data_holder->getTimestamp() is uint64_t which returns timestamp in milliseconds. Does my above code looks right?
I'd probably do something like this:
auto now = system_clock::now().time_since_epoch();
// Use the correct time duration below. Milliseconds could be wrong, see 1)
auto diff = now - std::chrono::milliseconds(data_holder->getTimestamp());
bool is_old = diff > std::chrono::seconds{120};
// bool is_old = diff > 120s; // From C++14 onwards.
1) As mentioned, milliseconds could be the wrong unit to use for getTimestamp(). All possible types are
std::chrono::hours
std::chrono::minutes
std::chrono::seconds
std::chrono::milliseconds
std::chrono::microseconds
std::chrono::nanoseconds
You probably have to try out which one to use, because that depends on data_holder->getTimestamp().
Note: Big one
Making sure to use system_clock to measure time since epoch will work most likely. But the standard doesn't require that a clock's epoch is the UNIX epoch. You have encountered this with steady_clock already.
You'd have to calculate the difference between the clock's epoch and the epoch yourself (and I don't know of a way to do that right now for any clock). For system_clock, if you don't trust it to use the unix epoch you can use the following:
system_clock::duration time_since_unix_epoch()
{
std::tm epoch;
epoch.tm_mday = 1;
epoch.tm_mon = 0;
epoch.tm_year = 70;
std::time_t epocht = mktime(&epoch);
return system_clock::now() - system_clock::from_time_t(epocht);
}
instead of system_clock::now(). I'd prefer this method.
Unfortunatly you can't just replace system_clock with another clock from std::chrono because only std::system_clock offers from_time_t(time_t) which converts a real date to the internal time_point used by the clock.

cleanest way to do relative time-of-day comparisons in c++11

Let's say I have a stream of events, each event with a full timestamp, spanning many days. I want to compare them against the time of day, but regardless of the day. For example, if a given event happened between 12:00:00 and 12:05:00, do something, but regardless of the day.
The event timestamps naturally fit as std::chrono::time_point objects. What is the most idiomatic way within std::chrono to do those comparisons? Is there an object that represents a time-of-day without being specific to a day? Do I have to roll my own?
You may do something like:
auto timePoint = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(timePoint);
auto ltime = std::localtime(&t); // or gmtime.
auto eventTime = std::chrono::hours(ltime->tm_hour)
+ std::chrono::minutes(ltime->tm_min);
auto lower_bound = std::chrono::hours(12) + std::chrono::minutes(0);
auto upper_bound = std::chrono::hours(12) + std::chrono::minutes(5);
if (lower_bound <= eventTime && eventTime <= upper_bound) {
// Do some action.
}
Is there an object that represents a time-of-day without being specific to a day? Do I have to roll my own?
I don't think so. But it should be trivial to implement. Convert the timepoint to the broken-down time std::tm, and then check the individual members.
#include <chrono>
#include <ctime> // struct tm, gmtime()
using std::chrono::system_clock;
std::time_t ts = system_clock::to_time_t (system_clock::now());
std::tm& time = *gmtime (&ts); // or localtime()
if (time.tm_hour==12 and time.tm_min>=0 and time.tm_min<5)
cout << "Inside interval\n";
Note: gmtime() and localtime() return a pointer to static data and hence are not thread-safe. Linux (and probably other *nix) has the thread safe gmtime_r() and localtime_r().

Adding two epoch millseconds in C++

My goal is to determine expiry of an item to when it was acquired(bought) and when it is sold.There is a TTL value associated with each of the item.
I am doing following :
time_t currentSellingTime;
long currentSystemTime = time(&currentSellingTime); // this gives me epoch millisec of now()
long TTL = <some_value>L;
long BuyingTime = <some_value> // this is also in epoch millsec
if(currentSystemTime > TTL+BuyingTime))
{
//throw exception
// item is expired
}
My question is how to sum two epoch millisec and compare it with another epoch millsec in C++
There may be some misconceptions on how time() works:
epoch time as given by time() is expressed in seconds, not millseconds
time returns the current time value and can optionally set current time in the variable given as its sole argument. This means that
long currentSystemTime = time(&currentSellingTime);
will set both currentSystemTime and currentSellingTime to the current time, and that's probably not what you intend to do... You should probably do
long currentSystemTime = time(NULL);
or
time(&currentSellingTime);
but the "double form" you are using is quite suspicious. For completeness' sake the MS Help reference for time()
You want to use another function, as as previously pointed out, time() returns seconds. Try:
#include <time.h>
long current_time() {
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return t.tv.sec * 1000l + t.tv_nsec / 1000000l;
}
Your code should work then. This approach is also POSIX compatible. Example usage:
const long TTL = 100;
long start_time = current_time();
while (!(current_time() > start_time + TTL))
{
// do the stuff that can expire
}
note: I know that the condition in the while loop can be constructed differently, but this way it is more like "until not expired".

difference seen in difftime and strftime values

I'm seeing a difference in time functions and was wondering what was the reason.
currently, I'm using localtime, mktime, strftime and difftime:
time_t ltime;
ltime = time(NULL);
StartTM = localtime(&ltime);
time_t time1 = mktime(StartTM );
char startbuffer [128];
strftime( start_buffer, 128, "%H:%M:%S", StartTM );
<<Do some stuff, take some time >>>
time_t ttime;
ttime = time(NULL);
StopTM = localtime(&ttime);
time_t time2 = mktime(StopTM );
char stop_buffer [128];
strftime( stop_buffer, 128, "%H:%M:%S:", StopTM );
double wtinsec = difftime(time2, time1);
Executed, the output looks like this:
Stop buffer=08:46:18
Start buffer=08:44:11
wtinsec=129
Subtracting start from stop by hand, the length of time is 2:07, however the total number of seconds (difftime) says 2:09. As both times are using the same raw data (time1, time2) for both calculations, my initial thoughts was combination of lack of precision in the strftime conversion and difftime is the cause of this.
But the difference is not constant. If the time between the 2 local calls is small (like 10 seconds) there is no difference. However, as the time between the 2 time calls gets longer, the difference in time totals becomes larger. At 2 mins, its 2 seconds at 5 mins its 4 seconds and so on...
Any reason why this is happening and is there anything more accurate (in C++) preferably in micro/milliseconds that can track time of day and subtract one from another?
Thanks.
The values in ltime and time1 should be identical; the round trip through localtime() and mktime() should give you the answer you started with. Similarly, of course, for ttime and time2.
This C code demonstrates the expected behaviour. You need to look hard at your code to find out what is going wrong.
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(void)
{
time_t ltime = time(NULL);
struct tm *start = localtime(&ltime);
time_t time1 = mktime(start);
char startbuffer[128];
strftime(startbuffer, sizeof(startbuffer), "%H:%M:%S", start);
printf("lt = %10lu, t1 = %10lu, time = %s\n",
(unsigned long)ltime, (unsigned long)time1, startbuffer);
sleep(10);
time_t ttime = time(NULL);
struct tm *finis = localtime(&ttime);
time_t time2 = mktime(finis);
strftime(startbuffer, sizeof(startbuffer), "%H:%M:%S", finis);
printf("lt = %10lu, t1 = %10lu, time = %s\n",
(unsigned long)ttime, (unsigned long)time2, startbuffer);
printf("diff time = %.2f\n", difftime(time2, time1));
return(0);
}
Sample output (from Mac OS X 10.7.5):
lt = 1358284665, t1 = 1358284665, time = 13:17:45
lt = 1358284675, t1 = 1358284675, time = 13:17:55
diff time = 10.00
I recommend looking at the values in your code, similar to the way I did. You might (or might not) print out the contents of the struct tm structures. It would be worth making a function to handle the 7-line block of repeated code; you'll need it to return time1 and time2, of course, so you can do the difference in the 'main' code. Also remember that localtime() may return the same pointer twice; you can't reliably use the start time structure after you've called localtime() with the finish time.