Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::future::wait_for not wait for the correct duration?

Tags:

c++

c++11

I don't understand why the discrepancy between the measured and the specified durations when calling std::future::wait_for increases when the specified duration increases.

When I tell a std::future to wait for 10ns and measure the elapsed time I get ~2000ns. Now, 10ns is a very short duration, so maybe there's too much overhead involved with the associated function calls to wait for this short amount of time. But when I tell a std::future to wait for 100000ns and measure the elapsed time I get ~150000ns. A similar effect can be seen when waiting for 10 and 100 microseconds, respectively.

#include <chrono>
#include <future>
#include <iostream>
#include <thread>

using namespace std::chrono;
using namespace std::chrono_literals;

void f() { std::this_thread::sleep_for(1s); }

int main() {
  steady_clock::time_point start, end;

  std::future<void> future = std::async(std::launch::async, f);

  start = steady_clock::now();
  future.wait_for(10ns);
  end = steady_clock::now();
  std::cout << "10 -> " << (end - start).count() << '\n';

  start = steady_clock::now();
  future.wait_for(100000ns);
  end = steady_clock::now();
  std::cout << "100000 -> " << (end - start).count() << '\n';

  return 0;
}

I compile the above code with g++ future_test.cpp -lpthread, with g++ 7.3.0 on Ubuntu 18.04.

I could explain something like

10 -> 2000
100000 -> 102000

But that's not what I get. Here's a representative result of multiple executions:

10 -> 2193
100000 -> 154723

Why is the measured duration for 100'000ns more than ~2'000ns from the specified duration?

like image 813
red Avatar asked Dec 01 '22 14:12

red


1 Answers

Quoting the documentation:

std::future_status wait_for( const std::chrono::duration& timeout_duration );

This function may block for longer than timeout_duration due to scheduling or resource contention delays.

like image 75
Davide Spataro Avatar answered Dec 05 '22 05:12

Davide Spataro