Boost timer 學習筆記

來源:互聯網
上載者:User

標籤:boost   timer   1-57   1-43   1-58   

今天開始看《Boost程式庫完全開發指南:深入C++“准”標準庫(第3版)》一書。我用的是boost 1.57,而書上使用的是boost 1.43左右。原以為差距不大,結果在第一個timer庫的時候就碰到了問題。

書上說的是直接使用boost::timer類。但是我查看原始碼時發現,timer現在只是一個命名空間而非一個類,真正的類是cpu_timer和auto_cpu_timer,同時,也沒有了elapsed_max和elapsed_min方法了。多了:is_stopped、start、resume和format方法。

在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時間。其中,真即時間易受其它程式運行幹擾,是不穩定的。如果是衡量演算法已耗用時間,更好的度量是user和system之和。從變數類型可以看出,所以的時間單位均為納秒(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: yes2.08s user + 0.00s system = 2.08s(99.6%)2.088596s real time

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Boost timer 學習筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.