c++11 - std::this_thread::sleep_for() 和纳秒

标签 c++11 g++ thread-sleep

如果我并排放置两个调用来确定最小可测量持续时间:

// g++ -std=c++11 -O3 -Wall test.cpp
#include <chrono>
typedef std::chrono::high_resolution_clock hrc;

hrc::time_point start = hrc::now();
hrc::time_point end   = hrc::now();
std::chrono::nanoseconds duration = end - start;
std::cout << "duration: " << duration.count() << " ns" << std::endl;

我已经循环运行了数千次,并且在我的特定 3.40GHz 桌面上始终获得 40 ns +/- 2 ns。

但是,当我查看我能睡的最短时间是多少时:

#include <thread>

hrc::time_point start = hrc::now();
std::this_thread::sleep_for( std::chrono::nanoseconds(1) );
hrc::time_point end   = hrc::now();
std::chrono::nanoseconds duration = end - start;
std::cout << "slept for: " << duration.count() << " ns" << std::endl;

这表明我平均 sleep 时间为 55400 纳秒,即 55.4 微秒。比我预期的时间长得多。

将上述代码放入 for() 循环中,我尝试 sleep 不同的量,结果如下:

  • sleep_for( 4000 ns ) => 休眠 58000 ns
  • sleep_for( 3000 ns ) => 休眠 57000 ns
  • sleep_for( 2000 ns ) => 休眠 56000 ns
  • sleep_for( 1000 ns ) => 休眠 55000 ns
  • sleep_for( 0 ns ) => 休眠 54000 ns
  • sleep_for( -1000 ns ) => 休眠 313 ns
  • sleep_for( -2000 ns ) => 休眠 203 ns
  • sleep_for( -3000 ns ) => 休眠 215 ns
  • sleep_for( -4000 ns ) => 休眠 221 ns

我有一些问题:

  • 如何解释这些数字?
  • 为什么休眠时间为负数会返回 200+ 纳秒,而休眠时间为 0+ 纳秒会返回 50,000+ 纳秒?
  • 负数作为 sleep 时间是一个已记录/受支持的功能,还是我无意中发现了一些我不能依赖的奇怪错误?
  • 是否有更好的 C++ sleep 调用可以为我提供更一致/可预测的 sleep 时间?

最佳答案

What could explain these numbers?

有一个非常明显的模式,您的所有结果始终比您请求的 sleep 时间长 54000ns。如果你看看 GCC 的 this_thread::sleep_for() 在 GNU/Linux 上是如何实现的,你会发现它只使用 nanospleep 并且正如 Cubbi 的评论所说,调用该函数可以大约需要50000ns。我猜想其中一些成本是进行系统调用,因此从用户空间切换到内核并返回。

Why does sleeping for a negative amount of time return 200+ ns, while sleeping for 0+ nanoseconds results in 50,000+ nanoseconds?

据我猜测,C 库会检查负数并且不会进行系统调用。

Is negative numbers as a sleep time a documented/supported feature, or did I accidentally stumble across some strange bug I cannot rely upon?

标准并不禁止传递负参数,因此是允许的,并且函数应该“立即”返回,因为相对超时指定的时间已经过去了。不过,您不能依赖负参数比非负参数返回得更快,这是您的特定实现的人为因素。

Is there a better C++ sleep call which would give me more consistent/predictable sleep times?

我不这么认为 - 如果我知道的话,我们就会在 GCC 中使用它来实现 this_thread::sleep_for()

编辑:在 GCC 的 libstdc++ 的最新版本中,我添加了:

if (__rtime <= __rtime.zero())
  return;

因此,当请求零或负持续时间时,不会有系统调用。

关于c++11 - std::this_thread::sleep_for() 和纳秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18071664/

相关文章:

c++ - 与 unordered_map vector 一起使用的 scoped_allocator_adaptor 的最小示例中的段错误

c++ - 从 std::string 中提取整数

c++ - Makefile导致编译错误

Java 简单图形循环很慢

java - 显示 30px 高的 JPanel,然后用 Minecraft 填充其余空间

java - ImageView 变化不够快

c++ - 使用C++ 11时列表中的编译错误

c++ - 如何在 Linux Mint 上安装 GCC 4.7.2?

c++ - C++ 模板的问题(大惊喜!)。为什么这行不通?

c++ - 使用不同的 enable_if 条件选择成员函数