Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::chrono::system_clock and duration<double>

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.

like image 675
Arno Duvenhage Avatar asked Apr 16 '26 02:04

Arno Duvenhage


2 Answers

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

like image 153
Jts Avatar answered Apr 17 '26 14:04

Jts


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.

like image 30
Arno Duvenhage Avatar answered Apr 17 '26 14:04

Arno Duvenhage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!