Boost学习记录--timer库

前言

转载自 https://www.cnblogs.com/nangning/p/3327901.html
https://www.cnblogs.com/hdtianfu/archive/2012/09/14/2684217.html

概述

目前旧版的boost::timer已经被替换,新版的有两个类
boost::timer::cpu_timer
boost::timer::auto_cpu_timer
auto_cpu_timer是一个更为精细的cpu_timer,当它被销毁的时候会自动的报告花费时间。

cpu_timer

这个类一般用来记录程序运行了多长时间,它被分解为经过时间,操作系统响应用户请求的时间和用户时间。

cpu_timer计量经过时间,用户执行时间,和系统执行时间。

void cpu_timer::start() noexcept;            // 开始一个计时器
void cpu_timer::stop()  noexcept;            // 结束一个计时器
void cpu_timer::resume() noexcept;           // 如果已经调用了stop,resume可以继续进行计时 
bool cpu_timer::is_stopped() noexcept;       // 计时器是否已经停止计时(call stop() ), 
 cpu_times cpu_timer::elapsed() noexcept;  // 如果is_stopped(),那么返回从 计时开始 至 stop()之间的时间间隔;
                                           // 否则, 返回从 计时开始 至 调用此函数 的时间间隔
 std::string format(int places, const string &format)const;
 std::string format(int places = default_places) const;
                                    //  返回 elapsed的字符串形式
                                    //  places代表精度,places = 3, 表示精确到小数点后3位,单位为秒
                                    //  format代表格式化字符串 ,常用的是%w,表示cpu_times.wall

//elapsed() 返回的类型
struct cpu_times
{
      nanosecond_type wall;       // most importent
      nanosecond_type user;
      nanosecond_type system;

      void clear();
};

用法


#include <boost/timer/timer.hpp>
#include <memory>
#include <vector>
#include <string>
#include <iostream>

using namespace std;
using namespace boost::timer;


vector<string> createVector_98()
{
    vector<string> vec;
    for (int i = 0; i < 10; ++i){
            vec.emplace_back("helloworld");
    }
    return vec;
}

vector<string> createVector_11()
{
    vector<string> vec;
    for (int i = 0; i < 100; ++i){
        vec.emplace_back("helloworld");
    }
    return move(vec);
}

int main()
{
    const int TEST_TIMES = 100;

    vector<string> result;

    cpu_timer timer;
    timer.start();
    for (int i = 0; i < TEST_TIMES; ++i){
        result = createVector_98();
    }
    cout << "no move" << timer.format(6) << endl;

    timer.start(); // don't call resume()
    
    for (int i = 0; i < TEST_TIMES; ++i){
        result = createVector_98();
    }
    cout << "use move" << timer.format(6) << endl;



	getchar();
}

//结果

 no move 0.025558s wall, 0.015600s user + 0.000000s system = 0.015600s CPU (61.0%)

use move 0.019096s wall, 0.031200s user + 0.000000s system = 0.031200s CPU (163.4%)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值