boost库中计时器的使用总结(timer)

Boost1.48版以后的timer库由两个组件组成:
    1. 早期的timer  (V1)    :使用的C/C++库函数std::clock()。其又包含3个小组件:
            1.1    计时器timer
            1.2    progress_timer
            1.3    progress_display
    2. 最新的cpu_timer  (V2):基于chrono库使用操作系统的API,计时精度更高。

虽然boost的timer库作为V1版已经不再使用了,由于初识boost,知道该使用最新的V2版本的计时器 cpu_timer,但对cpu_timer完全不熟悉。 所以在编写代码需要用计时器时就直接使用了,但是在使用中发现了其计时完全是错误的。

我加定时器的位置的函数是一个做增量索引的函数,由于线程较多,此thread会被在多个物理核上执行,发现时间被严重拉长了(正以上连接中的例子所示一样)。
再深层次的原因,暂时就不深入分析了,将来无意间发现也好,碰不到也罢,随遇而安!

关于boost的cpu_timer库:
解决的办法可能是使用cpu_timer了,现在还没有使用,等使用了再来补全此部分!
关于boost的cpu_timer库:
现在使用的一个可行的解决办法是调用izenelib/include/util/ClockTime.h中的ClockTimer,其具体实现如下:
#ifndef UTIL_CLOCK_TIMER_H
#define UTIL_CLOCK_TIMER_H
/**
 * @file util/ClockTimer.h
 * @author Ian Yang
 * @date Created <2009-05-06 09:34:37>
 * @date Updated <2010-06-25 15:06:09>
 * @brief Timer using wall clock instead of CPU ticks.
 *
 * In some performance measurement, the total elapsed time is more important
 * than just process or CPU time. @p izenelib::util::ClockTimer is such a tool
 * recording the total elapsed time.
 *
 * Because it use the Boost Date Time library, you may need to link that
 * library.
 */
#include <sys/time.h>

namespace izenelib {
namespace util {

/**
 * @brief A timer object similar to @p boost::timer but measures total elapsed
 * time instead of CPU time.
 *
 * This class measures wall clock rather than CPU time. Make your environment
 * clean because other processes can occupy the CPU, and the time is still counted.
 *
 * If CPU time measurement is intended, please use @p boost::timer in file
 * "boost/timer.hpp"
 */
class ClockTimer
{
public:
    /**
     * @brief remembers start time during construction
     */
    ClockTimer()
    : start_()
    {
        gettimeofday(&start_, 0);
    }

    /**
     * @brief resets start time to current time.
     */
    void restart()
    {
        gettimeofday(&start_, 0);
    }

    /**
     * @brief returns elapsed seconds since remembered start time.
     *
     * @return elapsed time in seconds, some platform can returns fraction
     * representing more precise time.
     */
    double elapsed() const
    {
        timeval now;
        gettimeofday(&now, 0);

        double seconds = now.tv_sec - start_.tv_sec;
        seconds += (now.tv_usec - start_.tv_usec) / 1000000.0;

        return seconds;
    }

private:
    timeval start_; /**< remembers start time */
};

}} // namespace izenelib::util

#endif // UTIL_CLOCK_TIMER_H



注意:gettimeofday函数本身就是一个linux的API函数,包含在头文件<sys/time.h>中,其精度可以达到微妙。



另外:上图中所说的processor/CPU time ,wall time 的精确含义是什么还是不太清楚?如果有行家看到,还望不吝赐教!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值