#include <iostream>
#include <chrono>
#include <thread>
// 使用 C++11 的 chrono 库来实现一个简单的计时器
class Timer {
public:
Timer() : start_(std::chrono::high_resolution_clock::now()) {}
~Timer() {
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start_;
std::cout << "Time elapsed: " << duration.count() << " seconds." << std::endl;
}
private:
std::chrono::time_point<std::chrono::high_resolution_clock> start_;
};
void some_function() {
// 模拟一些耗时操作
std::this_thread::sleep_for(std::chrono::seconds(2));
}
int main() {
{
Timer t; // 创建计时器对象,开始计时
some_function(); // 执行需要计时的函数
} // 计时器对象被销毁,输出耗时
return 0;
}
#include <iostream>: 引入标准输入输出库,用于打印信息。#include <chrono>: 引入 C++11 的 chrono 库,用于高精度计时。#include <thread>: 引入线程库,用于模拟耗时操作(如 sleep_for)。class Timer: 定义一个计时器类。some_function(): 模拟一个耗时操作,使用 std::this_thread::sleep_for 暂停程序执行 2 秒钟。main(): 主函数中创建 Timer 对象,调用 some_function(),当 Timer 对象超出作用域时自动析构并输出耗时。通过这种方式,可以很方便地测量一段代码的执行时间。
上一篇:图形化c++编程
下一篇:c++ float 保留两位小数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站