- Boost程序库完全开发指南:深入C++”准”标准库(第5版)
- 罗剑锋
- 450字
- 2020-08-27 16:45:18
2.3 progress_timer
progress_timer也是一个计时器,它派生自timer,会在析构时自动输出时间,省去了timer手动调用elapsed()的工作,是一个相当方便的自动计时的小工具。
progress_timer位于名字空间boost,需要包含的头文件如下:

2.3.1 用法
progress_timer继承了timer的全部功能,可以像使用timer那样使用它。例如:

但progress_timer有更简单的用法,不需要进行任何调用,只要声明progress_timer对象就可以了:


这样,在程序退出(准确地说是离开main函数局部域)导致progress_timer析构时,会自动输出流逝的时间,输出显示如下:
0.19 s
如果要在一个程序中测量多个时间,可以用花括号“{}”限定progress_timer的生命期:

只需要声明progress_timer的实例就能完成所需的全部工作,非常容易操作。有了progress_timer,程序员今后在做类似性能测试等计算时间的工作时将会感到轻松很多。
2.3.2 类摘要
progress_timer的类摘要如下:

progress_timer继承自timer,因此它的接口与timer相同,也很简单。唯一需要注意的是其构造函数,它允许将析构时的输出定向到指定的输入输出流里,默认是std::cout。如果有特别的需求,可以用其他标准库输出流(ofstream、ostringstream)将其替换,或者用cout.rdbuf()重定向cout的输出。
例如,下面的代码就把progress_timer的输出转移到了stringstream中,它可以被转换为字符串供其他应用使用:
