C++ Logo

std-discussion

Advanced search

Adding real_time_factor to Clock requirements for simulation

From: Daniele E. Domenichelli <ddomenichelli_at_[hidden]>
Date: Thu, 6 Jun 2019 15:22:21 +0200
Hello,

In simulation, it is possible to have a simulated clock that is not
steady and runs faster than the actual system clock.

All the implementations that I have seen so far for
std::this_thread::sleep_until for not-steady clocks do something like this:

    auto __now = _Clock::now();
    while (__now < __atime)
    {
        sleep_for(__atime - __now);
        __now = _Clock::now();
    }

where sleep_for does not take into account the clock used, and therefore
puts the thread to sleep for the expected time, but using the system
clock instead of the custom clock.

This works if _Clock is the system_clock, works but with several wake
ups if _Clock is slower than the system_clock, but it will always sleep
too much if _Clock is faster than the system_clock.
This is probably ok for the standard, but it's not optimal, especially
if you are trying to simulate something as fast as possible.

I already tried to find an alternative solution [1,2], but the only
workaround that I found is to specialize std::this_thread::sleep_until
for my clock [3] and unfortunately, even if this works on all the
compiler I tried, it is undefined behaviour. The only "legal"
alternative is not to use std::this_thread::sleep_until.

Therefore, I would like to discuss the idea of adding a
'real_time_factor' (that would be 1.0 for most clocks) to the Clock
requirement [4] that could be taken into consideration inside sleep_until:

    auto __now = _Clock::now();
    while (__now < __atime)
    {
        sleep_for(_Clock::duration(static_cast<_Clock::rep>(
            (__atime - __now).count() / _Clock::real_time_factor)));
        __now = _Clock::now();
    }


Thanks in advance for any comment.

Regards,
 Daniele


[1]https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87679
[2]https://www.reddit.com/r/cpp/comments/awy8ya/
[3]https://gcc.godbolt.org/z/-ELNWB
[4]http://eel.is/c++draft/time.clock.req

Received on 2019-06-06 08:24:23