从Boost1.48以后,timer库分为两部分:早期的timer和新的cpu_timer。
其中timer精度不高,跨度小,而cpu_timer则可弥补这一缺点。
1. timer
#include <boost/timer.hpp>
#include <iostream>
using namespace boost;
using namespace std;
int main()
{
//测试timer,已逐渐被废弃
timer t;
for(int i=0;i<1000;i++)
for(int j=0;j<1000;j++);
cout<<t.elapsed()<<"秒";
//输出0.01秒
}
2. progress_timer
#include <boost/progress.hpp>
#include <iostream>
#include <sstream>
using namespace boost;
int main()
{
//测试progress_timer,继承自timer,在析构时会自动输出时间
//第一种,默认cout作为输出流
progress_timer t;
for(int i=0;i<10000;i++)
for(int j=0;j<1000;j++);
//程序结束时输出时间
//第二种,以其它输出流来替换如ofstream,stringstream
/*stringstream ss;
{
progress_timer t(ss);
for(int i=0;i<10000;i++)
for(int j=0;j<1000;j++);
}
cout<<ss.str();*/
//输出0.01s
}
#include <boost/progress.hpp>
#include <iostream>
using namespace boost;
using namespace std;
int main()
{
//progress_display库,向屏幕显示进度
progress_display progress(100);
for(int i=0;i!=100;i++)
progress++;
//输出
//0% --10 -- 20-- 30 -- 40 -- 50 -- 60 -- 70-- 80-- 90-- 100%
//|----|----|----|----|----|----|----|----|----|----|
//***************************
}
4. cpu_timer
#include <boost/timer/timer.hpp>
#include <iostream>
using namespace boost::timer;
using namespace std;
int main()
{
//关于cpu_timer,比timer精度更高
cpu_timer t;
for(int i=0;i<10000;i++)
for(int j=0;j<1000;j++);
//t.format()默认6位小数,
//默认输出格式为"%ws wall,%us user+%ss system=%ts CPU (%p%)\n"
//%w 为墙上时间
//%u 为用户CPU时间
//%s 为系统CPU时间
//%t 为总计CPU时间
//%p 为总计CPU时间占墙上时间的比例
cout<<t.format();
//更改输出格式
/*string fmt("%ws,%us,%ss=%ts cpu %p%\n");
string fmt1("进程运行时间%ws\n");
cout<<t.format(7,fmt);*/ //小数点后7位
}