【发布时间】:2017-07-26 12:48:07
【问题描述】:
当我运行这段代码时
#include <iostream>
#include <boost/thread.hpp>
#include <boost/chrono/thread_clock.hpp>
void foo() {
boost::this_thread::sleep(boost::posix_time::microseconds(500));
}
int main() {
boost::chrono::thread_clock::time_point start = boost::chrono::thread_clock::now();
foo();
boost::chrono::thread_clock::time_point stop = boost::chrono::thread_clock::now();
std::cout << "duration = "
<< boost::chrono::duration_cast<boost::chrono::microseconds>(stop-start).count()
<< " microsec\n";
}
我得到以下输出:
duration = 121 microsec
duration = 121 microsec
duration = 110 microsec
duration = 114 microsec
另外,当我用不同的值替换500 时,例如200,输出总是在100 附近。使用-O3 编译。为什么时间不一致?
PS:我读到 sleep 已被弃用,但是当我用
boost::this_thread::sleep_for(boost::chrono::microseconds(200));
输出在 ~20 微秒的范围内。
【问题讨论】:
-
thread_clock衡量什么? -
@PeteBecker thread_clock class provides access to the real thread wall-clock,或者这是一个反问的问题,我忽略了一些明显的东西?
-
thread_clock 测量线程中实际花费的 CPU 时间。睡眠不会增加这个数字(或者至少,它只会增加一点)。
-
当一个线程休眠时,它不使用 CPU 时间,所以看起来“真正的线程挂钟”不会显示使用太多时间。查看系统范围的挂钟(
std::chrono::system_clock或其他变体之一)以查看睡眠时间。 -
@PeteBecker 我一直认为挂钟/挂钟测量实时包括睡眠而不是 CPU 时间。无论如何,我会尝试使用
system_clock
标签: c++ boost benchmarking