boost之timer

1. timer类实现

#pragma once

#include <ctime>
#include <limits>  

class timer
{
public:
    timer(){ _start_time = clock(); }
    void restart(){ _start_time = clock(); }
    double elapsed() const
    {
        return (double)(clock() - _start_time) / CLOCKS_PER_SEC; 
    }
    double elapsed_min() const
    {
        return (double)(1) / (double)CLOCKS_PER_SEC;
    }
    double elapsed_max() const
    {
        return (double)(std::numeric_limits<clock_t>::max() - _start_time) / double(CLOCKS_PER_SEC);
        
    }
private:
    clock_t _start_time;
};

2. 重点说明

2.1 CLOCKS_PER_SEC

  timer的计数使用了标准头文件<ctime>里的clock()函数,它返回自进程启动以来的clock计数,每秒的clock数由宏CLOCKS_PER_SEC定义,CLOCKS_PER_SEC的值因操作系统而不同,在win32下是1000,而在linux下则是1000000,页就是说在win32下的精度是毫秒,在linux下的精度是微妙。

2.2 numeric_limits模版

  说白了,它是一个模板类,它主要是把C++当中的一些内建型别进行了封装,比如说numeric_limits<int>是一个特化后的类,从这个类的成员变量与成员函数中,我们可以了解到int的很多特性:可以表示的最大值,最小值,是否是精确的,是否是有符号等等。如果用其他任意(非内建类型)来特化这个模板类,比如string,string怎么可能有最大值?我们从MSDN上可以了解到,这对string,成员变量与成员函数是没有意义的,要么返回0要么为false。 

  参考博客:http://blog.163.com/wujiaxing009%40126/blog/static/7198839920124135147911/

2.3 使用建议

  timer不适合高精度的时间测量任务,它的精度依赖操作系统或编译器,难以做到跨平台,timer也不适合大跨度时间段的测量,可提供的最大时间跨度只有几百个小时,如果需要以天、月甚至年作为时间的单位则不能使用timer,应使用date_time.

3. 扩展new_progress_timer

3.1 代码实现

template<int N = 2>
class new_progress_timer : public timer
{
public:
    new_progress_timer(ostream &os = cout)
        :m_os(os)
    {

    }

    ~new_progress_timer()
    {
        try
        {
            // 保存流的状态
            ostream::fmtflags old_flags = m_os.setf(ostream::fixed, ostream::floatfield);
            streamsize old_prec = m_os.precision(N);

            // 输出时间
            m_os << elapsed() << "s\n" << endl;

            // 恢复流状态
            m_os.flags(old_flags);
            m_os.precision(old_prec);
        }
        catch (...){}
    }
private:
    ostream &m_os;   // 需要特别注意
};

继承于timer类,主要实现输出时间的精度控制

注意代码的最后一行,原因是:

protected:
    __CLR_OR_THIS_CALL basic_ostream(_Myt&& _Right)
        {    // construct by moving _Right
        _Myios::init();
        _Myios::move(_STD move(_Right));
        }

    _Myt& __CLR_OR_THIS_CALL operator=(_Myt&& _Right)
        {    // move from _Right
        this->swap(_Right);
        return (*this);
        }

    void __CLR_OR_THIS_CALL swap(_Myt& _Right)
        {    // swap with _Right
        if (this != &_Right)
            _Myios::swap(_Right);
        }

public:
    __CLR_OR_THIS_CALL basic_ostream(const _Myt&) = delete;
    _Myt& __CLR_OR_THIS_CALL operator=(const _Myt&) = delete;

 

  

转载于:https://www.cnblogs.com/xiaobingqianrui/p/9177655.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值