如果我并排放两个电话来确定最小的可测量持续时间:
// 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;
这告诉我平均睡眠时间为55400纳秒,即55.4微秒。远远超过我的预期。
将上面的代码放入 for()
循环,我尝试睡不同的数量,这是结果:
- 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+ ns,而睡眠时间为0+纳秒会导致50,000+纳秒?
- 负数作为睡眠时间是一个记录/支持的功能,还是我不小心偶然发现了一些我不能依赖的奇怪错误?
- 是否有更好的C ++睡眠调用可以让我更加一致/可预测的睡眠时间?