天天看點

boost學習之二(時間 timer庫)

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

timer有兩個元件組成 早起的timer(v1)和新的cpu_timer(V2)。  cpu_timer(v2) 之後詳細說明,本篇文章暫時隻講解timer(v1)

timer(v1) 庫包含三個元件。   計時器timer、progress_timer和進度訓示器progress_display.

1、timer是一個小型的計時器,提供毫秒級别的計時精度。程式員可以手工控制使用。

   用法:

#include "boost/progress.hpp"
#include <iostream>
using namespace boost;
int main()
{
 	timer t;
	// 可度量的最大時間,一小時為機關
 	std::cout << "max timespan:" << t.elapsed_max()/3600 << "h" << std::endl;
	// 可度量的最小時間,以秒為機關
 	std::cout << "min timespan:" << t.elapsed_min() << "s" << std::endl;
	// 輸出已經流逝的時間
 	std::cout << "now time elapsed:" << t.elapsed() << "s" << std::endl;
	getchar();
	return 0;
}
           

注意包含的頭檔案#include "boost/progress.hpp" 必須是你自己配置好的例如在vs2012中的附加包含目錄下要把boost所在位置注明

列印結果是

boost學習之二(時間 timer庫)

2、progress_timer

  progress_timer也是一個計時器,它繼承自timer。不過在調用析構時會自動輸出時間

  用法:

#include <iostream>
#include <windows.h>
#include "boost/progress.hpp"
using namespace boost;
int main()
{
	// 注意生命一個對象之後當生命周期結束的時候會自動調用析構函數進而實作列印, 是以可以直接用{}來确定他的生命周期
	{
		progress_timer t;			// 第一個計時
		Sleep(2000);
	}
	{
		progress_timer t2;			// 第二個計時器
		Sleep(3000);
	}

	// 也可以不加大括号用法和timer一樣
	{
		progress_timer t3;						// 第三個計時器
		Sleep(4000);
		std::cout << t3.elapsed() << std::endl;
	}

	getchar();
	return 0;
}
           

列印結果是:

boost學習之二(時間 timer庫)

注意最後列印了兩次4一次是調用的elapsed()函數列印的 ,一次是生命周期直接調用的析構函數列印的。

3、progress_display可以在控制台上顯示程式的執行進度,他能夠提供一個友好的使用者界面,即類似于load界面。

   用法:

#include <iostream>
#include "boost/progress.hpp"
#include <windows.h>
#include <vector>

using namespace boost;

int main()
{
	std::vector<std::string> v(100);
	progress_display pd(v.size());

	std::vector<std::string>::iterator it = v.begin();
	for (; it != v.end(); ++it )
	{
		Sleep(1000);
		pd++;
	}

	getchar();
	return 0;
}
           

列印結果:

boost學習之二(時間 timer庫)

實際上就是列印一個進度條來顯示目前進度的

注意:progress_display無法把進度顯示輸出與程式的輸出分離

繼續閱讀