2

i.e. i'm using std::this_thread::sleep_for(std::chrono::milliseconds(10)); in a program loop.

If I have a variable that gets incremented on this loop to show seconds elapsed, what do I need to increment by?

i.e. float x = 0;

for each step:

x += 0.01

I've tried 0.1, 0.01, 0.001, but they all seem either too fast or too slow.

Stephen K
  • 697
  • 9
  • 26
  • 1
    `std::this_thread::sleep_for(std::chrono::milliseconds(10));` may not be accurate. You probably should use this approach (one in the example) instead: http://en.cppreference.com/w/cpp/thread/sleep_for – drescherjm Dec 24 '17 at 20:59
  • I recommend using `sleep_until` and using an absolute time point. That way you avoid drift. – Galik Dec 24 '17 at 21:10
  • 3
    You need to obtain **real duration** of the elapsed sleep period: save start time before going to sleep (by calling `chrono::high_resolution_clock::now()` for example), then save end time after sleep and finally subtract those values. Then you can cast this duration to milliseconds or seconds or whatever. – user7860670 Dec 24 '17 at 21:11
  • You would need to increament by 10/1000 or 1/100 or .01 – Jake Freeman Dec 24 '17 at 21:12
  • 1
    `seconds{1} - milliseconds{10}` But Galik's comment concerning `sleep_until` is the best advice. – Howard Hinnant Dec 24 '17 at 21:16
  • There will be some round off error adding .01 multiple times. Also you likely will not get exactly 10 ms of sleep adding further error. That is why you need to compare between time points instead of incrementing .01 – drescherjm Dec 24 '17 at 21:18

2 Answers2

8

I would recommend using absolute time points and wait_until(). Something like this:

// steady_clock is more reliable than high_resolution_clock
auto const start_time = std::chrono::steady_clock::now();
auto const wait_time = std::chrono::milliseconds{10};
auto next_time = start_time + wait_time; // regularly updated time point

for(;;)
{
    // wait for next absolute time point
    std::this_thread::sleep_until(next_time);
    next_time += wait_time; // increment absolute time

    // Use milliseconds to get to seconds to avoid
    // rounding to the nearest second
    auto const total_time = std::chrono::steady_clock::now() - start_time;
    auto const total_millisecs = double(std::chrono::duration_cast<std::chrono::milliseconds>(total_time).count());
    auto const total_seconds = total_millisecs / 1000.0;

    std::cout << "seconds: " << total_seconds << '\n';
}
Galik
  • 47,303
  • 4
  • 80
  • 117
0

how many 10 ms periods in one second.

  1 sec / 10 ms == 1000 ms / 10 ms == 100  (10 ms periods per second) 

But see also: https://stackoverflow.com/a/37445086/2785528

2785528
  • 5,438
  • 2
  • 18
  • 20