Boost cpu_timer 学习笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pdcxs007/article/details/47281391

cpu_timer类和auto_cpu_timer类用于精确计时,有elapsedstartis_stopped等方法。在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

猜你喜欢

转载自blog.csdn.net/pdcxs007/article/details/47281391
今日推荐