Boost中的Timer的使用——计算时间流逝
2014-07-05 19:47
369 查看
使用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:使用local_date_time 计算当前时间戳
- Firefox - 附加软件 - Firebug - Console控制台视图 - 使用console.time()计算时间
- 使用DATEDIFF函数计算时间差
- Boost.asio的简单使用(timer,thread,io_service类)
- C#中使用TimeSpan计算两个时间的差值
- C#里如何使用Timespan(计算时间差)
- 还有更好的写法吗(使用Timer来判断鼠标在控件上停留的时间)
- symbian 时间使用和统计(计算)函数(类)运行时间
- symbian 时间使用和统计(计算)函数(类)运行时间
- 如何利用windosAPI计算程序运行时间 不使用VC的库,也就是说不跨系统,跨编译器
- boost学习之 时间和日期 timer
- C#中使用TimeSpan计算两个时间的差值
- C#中使用TimeSpan计算两个时间的差值
- C#中使用TimeSpan计算两个时间的差值
- 计算mp3时间以及位速工具(使用JMF框架)
- 使用 DurationFormatUtils 计算时间间隔
- C#中使用TimeSpan计算两个时间的差值
- [转]C#中使用TimeSpan计算两个时间的差值
- WinForm中使用timer显示当前时间
- Windows中如何计算时间间隔(1)使用CTime 和CTimeSpan