Boost中的Timer的使用——计算时间流逝
使用Boost中的Timer庫計算程序的運行時間
? ? ?程序開發人員都會面臨一個共同的問題,即寫出高質量的代碼完畢特定的功能。評價代碼質量的一個重要標準就是算法的運行效率,也就是算法的運行時間。為了可靠的提高程序的運行效率,首先要知道運行程序所消耗的時間,然后找出可行的方案對程序進行優化。C++程序猿在開發代碼的過程中難免會遇見此類問題,本文以Boost中的Timer庫為例。具體解說怎樣測量程序的運行時間。
Boost中Timer庫的介紹
Timer是Boost中的一個非常小的時間庫。提供時間度量和進度顯示功能。當中包括三個組件:(1)計時器類timer、timer類的子類progress_timer類和進度指示類progress_display。
1、 timer
timer位于boost命名空間中,使用之前須要包括頭文件<boost/timer.hpp>
timer中有3個函數,分別為:(1)elapsed_max(),返回可度量的最大時間間隔;(2)elapsed_min(),返回可度量的最小時間間隔。(3)elapsed(),返回timer類創建到elapsed()函數調用時所流逝的時間。
比如採用timer類測量std::cout<<"helloworld"<<std::endl;語句的運行時間,程序例如以下所看到的:
#include<iostream>
#include<cstdlib>
using namespace std;
#include <boost/timer.hpp>
using namespace boost;
int main(int argc, char ** argv)
{
? ? timer ter; //創建對象時就開始計時
? ? std::cout<<"helloworld"<<std::endl;
? ? std::cout<<ter.elapsed()<<std::endl;//輸出程序運行所消耗的時間,以秒為單位。
? ? std::cout<<ter.elapsed_max()<<std::endl;//輸出timer類可以度量的最大時間間隔。以秒為單位。
? ? std::cout<<ter.elapsed_min()<<std::endl;//輸出timer類可以度量的最小時間間隔。以秒為單位。
? ? return EXIT_SUCCESS;
}
程序運行結果例如以下圖所看到的:
2 、 progress_timer類
? progress_timer類是timer類的子類,此類具有一定的特殊性,在系統對此類對象進行析構時會自己主動調用此類的elapsed()函數。輸出系統運行程序所消耗的時間。
使用progress_timer類須要包括<boost/progress.hpp>頭文件
#include <iostream>
#include <cstdlib>
using namespace std;
#include <boost/progress.hpp>
using namespace boost;
int main(int argc, char **argv)
{
boost::progress_timer pt;
std::cout<<"helloworld"<<std::endl;
std::cout<<pt.elapsed()<<std::endl;//手動調用elapsed()函數,輸出程序運行時間
return EXIT_SUCCESS;
}
結果例如以下圖所看到的:
3、progress_display類
? ?progress_display類用于顯示程序的運行進度。使得用戶獲得動態感。
使用前須要包括<boost/progress.hpp>頭文件
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
#include <boost/progress.hpp>
using namespace boost;
int main(int argc, char **argv)
{
std::vector<int> vec(10000);
//申明進度條
boost::progress_display pd(vec.size());
for (int i=0; i<100; i++)
{
vec.push_back(i);
}
return EXIT_SUCCESS;
}
程序運行結果例如以下圖所看到的:
總結
以上是生活随笔為你收集整理的Boost中的Timer的使用——计算时间流逝的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows任务管理器有哪些快捷键
- 下一篇: 开学考试!!