c++ - 为什么 std::future::wait_for 不等待正确的持续时间?

标签 c++ c++11

我不明白为什么调用 std::future::wait_for 时测量的持续时间和指定的持续时间之间的差异会随着指定持续时间的增加而增加。

当我告诉 std::future 等待 10ns 并测量耗时时,我得到 ~2000ns。现在,10 纳秒是一个非常短的持续时间,所以可能相关函数调用涉及太多开销以等待这么短的时间。但是当我告诉 std::future 等待 100000ns 并测量耗时时,我得到 ~150000ns。分别等待 10 微秒和 100 微秒时,可以看到类似的效果。

#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;
}

我用 g++ future_test.cpp -lpthread 编译上面的代码,在 Ubuntu 18.04 上用 g++ 7.3.0。

我可以解释一下

10 -> 2000
100000 -> 102000

但这不是我得到的。这是多次执行的代表性结果:

10 -> 2193
100000 -> 154723

为什么 100'000ns 的测量持续时间比指定持续时间多 ~2'000ns?

最佳答案

引用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.

关于c++ - 为什么 std::future::wait_for 不等待正确的持续时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55748416/

相关文章:

c# - 在 .NET 控件中部署非托管依赖 dll

c++ - 下标运算符的标准 C++ 函数对象模板

c++ - 在 C 程序中调用 C++ 共享库...如何管理?

c++ - 将 std::function 转换为不同的 std::function 并调用它?

c++ - 从绑定(bind)与 lambda 函数中获取 operator() 的类型

c++ - 使用 std::transform 将 std::vector 容器转换为 std::set

c++ - 检查给定日期是夏令时还是冬令时的例程

c++ - 为什么一次打印一个字符比预先连接它们慢?

c++ - 无法编译代码,因为它在 C++11 中已弃用

c++ - std::strcpy 未在此范围内声明 DESPITE #include <cstring>