標籤: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 學習筆記