【问题标题】:boost::thread_sleep vs boost::chrono::thread_clock inconsistentboost::thread_sleep 与 boost::chrono::thread_clock 不一致
【发布时间】: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


【解决方案1】:

确实,我忽略了一些明显的东西。 documentation 说:

thread_clock 类提供对真正线程挂钟的访问,即 调用线程的实际 CPU 时间时钟。

我认为 wall-time 是经过的实际时间,而不是不包括线程睡眠时间的 cpu-time。无论如何,为了获得一致的数字,我不得不改用boost::chrono::system_clock

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    相关资源
    最近更新 更多