boost的timer类可以计算时间的流逝,可以用来测量程序的运行时间,算法的执行时间等,提供毫秒级别的时间精度,最大的时间间隔是596小时.
boost::timer 和 boost::progress_timer 通常只提供 秒级或毫秒级精度,不适合高精度性能分析。
推荐使用 boost::chrono 进行高精度计时,
boost::chrono 提供了与 C++11 <chrono> 兼容的高精度时钟,支持 纳秒级 计时。
#include <boost/timer.hpp> // boost::timer
#include <boost/progress_timer.hpp> // boost::progress_timer
#include <iostream>
void example_timer() {
boost::timer t; // 开始计时
// 模拟一些工作
for (int i = 0; i < 1000000; ++i) {
volatile double x = i * i;
}
double elapsed = t.elapsed(); // 获取已耗时间(秒)
std::cout << "⏱️ 工作耗时: " << elapsed << " 秒" << std::endl;
}
// boost::progress_timer:自动输出耗时
void example_progress_timer() {
{
boost::progress_timer pt; // 开始计时,析构时自动输出
// 模拟耗时操作
for (int i = 0; i < 2000000; ++i) {
volatile double x = std::sqrt(i);
}
// 析构时自动输出到 std::cout
} // <-- 在这里自动输出耗时
std::cout << "继续执行其他代码..." << std::endl;
}
// 高精度计时
#include <boost/chrono.hpp>
#include <iostream>
void example_chrono_timer() {
auto start = boost::chrono::high_resolution_clock::now();
// 模拟工作
for (int i = 0; i < 500000; ++i) {
volatile double x = std::sin(i);
}
auto end = boost::chrono::high_resolution_clock::now();
auto elapsed = boost::chrono::duration_cast<boost::chrono::microseconds>(end - start);
std::cout << "高精度耗时: " << elapsed.count() << " 微秒" << std::endl;
}