I can measure time using:
t1 = system_clock::now();
...
t2 = system_clock::now();
duration<double> d = t2 - t1;
That compiles fine, but how do I do the reverse? I want to move a time point using duration?
example (does not compile):
system_clock::time_point tp1 = system_clock::now();
system_clock::time_point tp2 = tp1 + duration<double>(1.0);
The system_clock::time_point '+' operator does not seem to accept duration<double>.
How can I move a time point by a duration specified using time in seconds (floating point value)? I need to use system_clock because it can convert to time_t.
Is this what you want?
system_clock::time_point tp1 = system_clock::now();
system_clock::time_point tp2 = tp1 + duration_cast<system_clock::duration>(duration<double>(1.5));
cout << duration_cast<milliseconds>(tp2 - tp1).count();
Output: difference is 1500ms
Live Demo
Ok, I went with the following (seeing as VS2012 might have a bug in 'duration_cast'). To add a time duration specified in seconds (using floating point) to a system_clock time point:
const double SECS_TO_SYSTEM_TICKS = (double)system_clock::period::den / (double)system_clock::period::num;
system_clock::time_point tp1 = system_clock::now()
double dTimeS = 1.0;
...
system_clock::duration d((system_clock::rep)(floor(dTimeS) * SECS_TO_SYSTEM_TICKS));
time_t t = system_clock::to_time_t(t1 + d);
I use 'floor(dTimeS)' just because in my implementation I do not want the fractional seconds to be rounded up to seconds.
The following should also work on a newer compiler (according to José's answer):
system_clock::duration d = duration_cast<system_clock::duration>(duration<double>(floor(dTimeS)));
time_t t = system_clock::to_time_t(t1 + d);
This also worked for me:
auto secs = seconds((seconds::rep)floor(dTimeS));
auto system_ticks = duration_cast<system_clock::duration>(secs);
time_t t = system_clock::to_time_t(t1 + system_ticks);
NOTE: The rounding behaviour (ticks to seconds) of 'to_time_t' is unspecified and if I need the fractional seconds I extract it separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With