boost库使用—timer
#### timer库简介
timer是一个很小的库,提供简单的时间度量和进度显示功能,也可用于性能测试等计时任务。timer库包含三个组件:计时器类timer、progress_timer和进度指示类progress_display。
计时器类timer
包含头文件
#include <boost/timer.hpp>
流程:
实例化对象时开始计时,调用elapsed()函数进行计时输出;
案例:
#include <iostream>
#include <windows.h>
#include <boost/timer.hpp>
using namespace std;
int main()
{
//开始计时
boost::timer t;
//可度量最大时间
cout << "max timespan:" << t.elapsed_max() / 3600 << "h" << endl;
//可度量最小时间
cout << "min timespac:" << t.elapsed_min() << endl;
//第一次计时
cout << "now time elapsed:" << t.elapsed() << endl;
Sleep(1000);
//第二次计时
cout << "now time elapsed:" << t.elapsed() << endl;
return 0;
}
输出:
max timespan:596.523h
min timespan:0.001
now time elapsed:0.001
now time elapsed:1.001
计时器类progress_timer
包含头文件:
#include <boost/progress.hpp>
流程:
实例化开始计时,自动析构并输出时间
说明:
progress_timer继承于timer,所以timer的函数也可以调用;
progress_timer计时是析构后自动输出;也可以多个计时,需要用{}包含
案例:
#include <iostream>
#include <windows.h>
#include <boost/progress.hpp>
using namespace std;
int main()
{
{
//多个计时
{
//第一个计时
//启动计时器
boost::progress_timer tt;
Sleep(100);
cout << "one progress time elapsed:" << tt.elapsed() << endl;
}
//第二个计时
{
boost::progress_timer tt;
Sleep(100);
//输出计时器数
cout << "two progress time elapsed:" << tt.elapsed() << endl;
//{}结束代表析构函数
}
}
system("pause");
return 0;
}
输出:
one progress time elapsed:0.1
0.10s
two progress time elapsed:0.1
0.10s
进度指示类progress_display
包含头文件:
#include <boost/progress.hpp>
流程:
实例化基数大小,然后++
这种现实存在弊端,不建议使用
案例:
#include <iostream>
#include <windows.h>
#include <boost/timer.hpp>
#include <vector>
#include <boost/progress.hpp>
using namespace std;
vector<string>v(100);
//申明基数大小
boost::progress_display pd(v.size());
for (auto it = v.begin(); it != v.end(); it++)
{
Sleep(100);
//正常使用,没有其他输出
//++pd;
cout << "hello progress_display" << endl;
//输出会打乱格式
pd.restart(v.size());
pd += (it-v.begin()+1);
}
system("pause");
return 0;
}
想了解学习更多C++后台服务器方面的知识,请关注:
微信公众号:C++后台服务器开发