现在的位置: 首页 > 综合 > 正文

Boost中的Timer的使用——计算时间流逝

2018年04月06日 ⁄ 综合 ⁄ 共 1781字 ⁄ 字号 评论关闭

使用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;
}

程序执行结果如下图所示:



抱歉!评论已关闭.