Boost cpu_timer 學習筆記

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章