码迷,mamicode.com
首页 > 其他好文 > 详细

Boost timer 学习笔记

时间:2015-08-04 21:09:18      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:boost   timer   1-57   1-43   1-58   

今天开始看《Boost程序库完全开发指南:深入C++“准”标准库(第3版)》一书。我用的是boost 1.57,而书上使用的是boost 1.43左右。原以为差距不大,结果在第一个timer库的时候就碰到了问题。

书上说的是直接使用boost::timer类。但是我查看源代码时发现,timer现在只是一个命名空间而非一个类,真正的类是cpu_timerauto_cpu_timer,同时,也没有了elapsed_maxelapsed_min方法了。多了:is_stoppedstartresumeformat方法。

elapsed方法中,返回的不再是一个数字,而是一个struct cpu_times,这个结构体中,定义为:

struct cpu_times
{
    nanosecond_type wall;
    nanosecond_type user;
    nanosecond_type system;

    void clear() {wall = user = system = 0LL; }
};

boost官方文档的说法,wall指的是程序运行的真实时间,user指的是用户CPU时间,system指系统CPU时间。其中,真实时间易受其它程序运行干扰,是不稳定的。如果是衡量算法运行时间,更好的度量是usersystem之和。从变量类型可以看出,所以的时间单位均为纳秒(ns)。

默认的输出格式为:

5.713010s wall, 5.709637s user + 0.000000s system = 5.709637s CPU (99.9%)

文档解释为:

In other words, this program ran in 5.713010 seconds as would be measured by a clock on the wall, the operating system charged it for 5.709637 seconds of user CPU time and 0 seconds of system CPU time, the total of these two was 5.709637, and that represented 99.9 percent of the wall clock time.

格式可以自定义,默认的格式定义为:

" %ws wall, %us user + %ss system = %ts CPU (%p%)\n"

含义为:

Sequence Replacement value
%w times.wall
%u times.user
%s times.system
%t times.user + times.system
%p The percentage of times.wall represented by times.user + times.system

auto_cpu_timer定义的时候,可将格式内容传入构造函数,以控制输出格式。

而对于cpu_timer类,有format函数,定义为:

std::string format(short places, const std::string& format);
std::string format(short places = default_places);

其中,places控制时间的小数点位数,format就是刚刚的格式字符串了。

主要内容就是这些了,现在看一下一个小例子吧:

#include <iostream>
#include <boost/timer/timer.hpp>
#include <cmath>

using namespace std;
using namespace boost;

int main()
{
    timer::cpu_timer t;
    timer::auto_cpu_timer auto_timer(6,
            "%ws real time\n");
    int a;

    for (long i = 0; i < 100000000; ++i)
        a = sqrt(i * i); // spend some time

    cout << "is started: " << (t.is_stopped() ?
        "no" : "yes") << endl;
    cout << t.format(2, "%us user + %ss system "
            "= %ts(%p%)") << endl;

    return 0;
}

需要注意的是,编译时需要链接boost相关库,而不是以前的可以直接运行:

g++ timer.cpp -o timer -lboost_timer -lboost_system

输出为:

is started: yes
2.08s user + 0.00s system = 2.08s(99.6%)
2.088596s real time

版权声明:本文为博主原创文章,未经博主允许不得转载。

Boost timer 学习笔记

标签:boost   timer   1-57   1-43   1-58   

原文地址:http://blog.csdn.net/pdcxs007/article/details/47281391

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!