Boost庫基礎-計時器timer庫

1.timer庫

timer是一個很小的庫,提供簡易的度量時間和進度顯示功能,可以用於性能測試等需要計時的任務。

timer庫包含三個小組件,分別是:計時器timer、progress_timer和進度指示器progress_display。

①timer類可以用於測試時間的流逝,是一個小型的計時器,提供毫秒級別的計時精度和操作函數。

用法:

#include <iostream>
#include <boost/timer.hpp>

using namespace std;
using namespace boost;

int main()
{
	timer t;
	//可度量的最大時間,以小時爲單位
	cout << "max timespan:" << t.elapsed_max() / 3600 << "h" << endl;

	//可度量最小時間,以秒爲單位
	cout << "min timespan:" << t.elapsed_min() << "s" << endl;

	//輸出已經流逝的時間
	cout << "now time elapsed:" << t.elapsed() << "s" << endl;

	getchar();
	return 0;
}

適用:適用於大部分要求不高的程序的計時任務,不適合高精度的測量任務,如果需要以天、月甚至更高時間單位則不能使用timer。

②progress_timer也是一個計時器,繼承自timer,它會在析構時自動輸出時間,省去了timer手動調用elapsed()的工作,它是一個用於自動計時相當方便的小工具。

用法:

#include <iostream>
#include <boost/progress.hpp>

using namespace std;
using namespace boost;

int main()
{
	progress_timer t;

	getchar();
	return 0;
}

這樣,在程序退出時導致progress_timer析構時,會自動輸出流逝的時間。

適用:測試程序性能。

#include <iostream>
#include <boost/progress.hpp>
#include <sstream>

using namespace std;
using namespace boost;

int main()
{
	stringstream ss;
	{
		progress_timer t(ss);
	}
	cout << ss.str();

	getchar();
	return 0;
}

上面的代碼將progress_timer 輸出轉移到了stringstream中。

③progress_display是一個獨立的類,與timer庫中的前面介紹的兩個組件沒有任何聯繫。

class progress_display : private noncopyable
{
 public:
  explicit progress_display( unsigned long expected_count_,
                             std::ostream & os = std::cout,
                             const std::string & s1 = "\n", //leading strings
                             const std::string & s2 = "",
                             const std::string & s3 = "" )
......
}

它的構造函數接受一個long型的參數expected_count_,表示用於進度顯示的基數。

用法:

#include <iostream>
#include <vector>
#include <fstream>
#include <boost/progress.hpp>

using namespace std;
using namespace boost;

int main()
{
	vector<string> v(100);
	//文件輸出流
	ofstream fs("./test.txt");

	progress_display pd(v.size());

	//遍歷,處理字符串,寫入文件
	for (auto& x : v)
	{
		fs << x << endl;

		//更新進度顯示
		++pd;
	}

	getchar();
	return 0;
}

運行截圖

上面的星號表示進度。

progress_timer 可以用作基本的進度顯示,但它有個固定的缺陷:無法把進度顯示與輸出 與 程序的輸出分離。

 

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