【问题标题】:Boost returning CPU time of 0提升返回 CPU 时间为 0
【发布时间】:2017-08-12 08:10:25
【问题描述】:

我正在尝试测量 C++ 程序中函数的 CPU 时间。我正在使用 boost 库执行此操作。然而,当我运行我的程序时,我得到了 0 秒的结果。我是新手,所以如果有人能指出我正确的方向吗?

我怎样才能让这个返回一个我可以实际使用的时间,比如 0.00156 之类的?

代码:在 main() 内部

boost::timer::cpu_timer timer;

std::cout << tree1.search("Cork") << std::endl;

//Print CPU TIME
boost::timer::cpu_times elapsed = timer.elapsed();
std::cout << " CPU TIME: " << (elapsed.user + elapsed.system) / 1e9 << " seconds" << std::endl;

【问题讨论】:

  • 如果你写double(1e9) 而不是1e9 会发生什么?
  • 返回相同的结果
  • 您是否尝试过打印出为elapsed.userelapsed.system 返回的原始值?你得到了什么?
  • 也许你的计时器分辨率真的很粗糙,而且工作不到一个滴答声。
  • 因此不应该超过 6 次比较才能找到匹配项(假设它是平衡的)。可能没有足够的时间超过一个计时器滴答声。

标签: c++ boost cpu-time


【解决方案1】:

你可以使用boostchrono;

boost::timer::cpu_timer timer;

std::cout << tree1.search("Cork") << std::endl;

//Print CPU TIME
boost::chrono::duration<double> elapsed = boost::chrono::nanoseconds(timer.elapsed().user);
std::cout << " CPU TIME: " << seconds.count() << "s\n" << " seconds" << std::endl;

【讨论】:

  • 这仍然没有区别。会不会是函数执行的时间不够长,CPU时间太小无法显示?
  • 虽然使用chrono 代替Boost 是个好主意。我怀疑它有更好的时间分辨率。我不希望这有什么不同。
猜你喜欢
  • 1970-01-01
  • 2014-11-21
  • 1970-01-01
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多