简体   繁体   English

如何从boost :: timer :: cpu_timer获取经过的时间(以秒为单位)?

[英]How to get elapsed time in seconds from boost::timer::cpu_timer?

The following rough code, based on the documentation , gives me the elapsed time in seconds from the timer object provided in boost. 以下粗略代码基于文档 ,给出了boost中提供的计时器对象所用的经过时间(以秒为单位)。

boost::timer::cpu_timer timer;
// ...do some work...
const boost::timer::nanosecond_type oneSecond(1000000000LL);
return timer.elapsed().user / oneSecond;

The problem with this method is that I have this uncomfortable magic number in my code. 这种方法的问题在于我的代码中有这个令人不舒服的幻数。 Is there some method within boost that can give me elapsed seconds out of the nanosecond_type value available from the call to elapsed().user , without having this magic number sitting in my code? 在boost中是否有一些方法可以让我从调用elapsed()。user中获得的nanosecond_type值中经过几秒钟 ,而没有在我的代码中使用这个神奇的数字?

(EDIT:) Conclusion: (编辑:)结论:

Based on the accepted answer, I ended up with this snippet in my production code: 根据接受的答案,我最终在我的生产代码中使用了这个片段:

boost::timer::cpu_timer timer;
// ...do some work...
auto nanoseconds = boost::chrono::nanoseconds(timer.elapsed().user + timer.elapsed().system);
auto seconds = boost::chrono::duration_cast<boost::chrono::seconds>(nanoseconds);
std::cout << seconds.count() << std::endl;

As @jogojapan suggested, boost::chrono would be a good choice. 正如@jogojapan所说, boost :: chrono将是一个不错的选择。 But you don't need the duration_cast<> if you use double as underlying type. 但是如果使用double作为基础类型,则不需要duration_cast <>。

typedef boost::chrono::duration<double> sec; // seconds, stored with a double
sec seconds = boost::chrono::nanoseconds(timer.elapsed().user);
std::cout << seconds.count() << "s\n"; // gives the number of seconds, as double.

One more addition: 还有一个补充:

double
getSeconds( const boost::timer::nanosecond_type& elapsed )
{
  return
    static_cast< double >(
      boost::chrono::nanoseconds( elapsed ).count()
    ) * boost::chrono::nanoseconds::period::num / boost::chrono::nanoseconds::period::den;
}

This you can call with timer.elapsed().user for example to get a double value of the elapsed time. 这可以通过timer.elapsed().user来调用,例如获取经过时间的double值。 This can obviously also transformed to std::chrono , if wanted / supported. 如果需要/支持,这显然也可以转换为std::chrono

您应该测量每个硬件运行时每纳秒的滴答数。看看( 定时器功能使用C ++以纳秒为单位提供时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM