码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-07-11 13:26:16      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:bsp   动态   span   font   stream   函数   显示   progress   包括   

使用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中的Timer的使用——计算时间流逝

标签:bsp   动态   span   font   stream   函数   显示   progress   包括   

原文地址:http://www.cnblogs.com/wzzkaifa/p/7150027.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!