【Boost】boost::timer庫用法與執行個體

來源:互聯網
上載者:User
// boost::timer庫, 用於效能測試等需要計時的任務。 // boost::timer不適合高精度的時間測量任務。 它的精度依賴於作業系統或編譯器,難以做到跨平台。 // boost::timer也不適合大跨度時間段的測量,可提供的最大跨度只有幾百個小時,如果需要以天、月甚至年作為時間的單位則不能使用timer。 應該使用 date_time庫。void test_timer(){// 聲明一個計時器對象,並開始計時!boost::timer t;long long sum = 0;for (int i = 0; i < 1000000 ; i++)sum = sum + i;// 計算時間差, 測量自對象建立後所流逝的時間。double dl = t.elapsed();std::cout << "now time elapsed:" << dl << std::endl;//可度量的最大時間,以秒為單位std::cout << "max timespan:" << t.elapsed_max() /3600 << "h" << std::endl;//可度量的最小時間,以秒為單位std::cout << "min timespan:" << t.elapsed_min() << "s" << std::endl;// 還有一個restart()開始重新計時t.restart();}// boost::progress_timer也是一個計時器,它繼承自timer,// 它會在析構時自動輸出時間,省去了boost::timer手動調用elapsed()的工作,是一個用於自動計時相當方便的小工具。void test_progress_timer(){boost::progress_timer pt;long long sum = 0;for (int i = 0; i < 10000000 ; i++)sum = sum + i;pt.elapsed();// 另外一種方法,不要用el{boost::progress_timer pt;// do_something();}   // pt析構時自動輸出資料流逝時間}void test_progress_display(){std::vector<std::string> v(1000000, "abcdefg");std::ofstream fs("d:\\test.txt");// 聲明一個progress_display 對象,基數是v的大小boost::progress_display pd(v.size());// 開始選代遍曆向量,處理字串std::vector<std::string>::iterator pos;for (pos = v.begin(); pos != v.end(); ++pos){fs << *pos << std::endl;++pd; // 更新進度顯示}}// 進度表在列印過程中出錯的處理void test_progress_display_restart(){std::vector<std::string> v(100 , "abcd");v[10] = "";v[23] = "";std::ofstream fs("d:\\test.txt");boost::progress_display pd(v.size());std::vector<std::string>::iterator pos;for (pos = v.begin(); pos != v.end(); ++pos){fs << *pos << std::endl;++pd;if (pos->empty()){std::cout << std::endl;std::cout << "Error: null string # " << (pos - v.begin())<< std::endl;pd.restart(v.size());pd += (pos - v.begin() + 1);}}}

test_progress_display_restart()啟動並執行結果:

0%   10   20   30   40   50   60   70   80   90   100%|----|----|----|----|----|----|----|----|----|----|******Error: null string # 100%   10   20   30   40   50   60   70   80   90   100%|----|----|----|----|----|----|----|----|----|----|*************Error: null string # 230%   10   20   30   40   50   60   70   80   90   100%|----|----|----|----|----|----|----|----|----|----|***************************************************

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.