推荐使用std::chrono测量C++代码运行时间,精度高且跨平台;通过记录起始和结束时间点并计算差值可得耗时,也可封装成Timer类方便复用。

在C++中,计算程序或某段代码的运行时间(耗时)有多种方法,常用的方式依赖于标准库中的高精度时钟。下面介绍几种实用且跨平台的方法。
std::chrono 是 C++11 引入的时间处理库,提供高精度、类型安全的时间操作,适合测量代码执行耗时。
基本步骤:记录起始时间 → 执行目标代码 → 记录结束时间 → 计算差值。
#include <iostream>
#include <chrono>
<p>int main() {
// 开始计时
auto start = std::chrono::high_resolution_clock::now();</p><pre class='brush:php;toolbar:false;'>// 你的代码段
for (int i = 0; i < 1000000; ++i) {
// 模拟工作
}
// 结束计时
auto end = std::chrono::high_resolution_clock::now();
// 计算耗时(微秒)
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "耗时: " << duration.count() << " 微秒" << std::endl;
return 0;}
立即学习“C++免费学习笔记(深入)”;
你可以将 microseconds 替换为 milliseconds 或 nanoseconds 来获取不同单位的结果。
来自 <ctime> 的 clock() 是较老的方式,测量的是 CPU 时钟周期,单位是“滴答”(clock ticks),通过 CLOCKS_PER_SEC 转换为秒。
#include <iostream>
#include <ctime>
<p>int main() {
clock_t start = clock();</p><pre class='brush:php;toolbar:false;'>// 你的代码
for (int i = 0; i < 1000000; ++i) {}
clock_t end = clock();
double duration = (double)(end - start) / CLOCKS_PER_SEC;
std::cout << "耗时: " << duration << " 秒" << std::endl;
return 0;}
立即学习“C++免费学习笔记(深入)”;
注意:clock() 测量的是 CPU 时间,多线程或系统等待时可能不准确,不推荐用于高精度测量。
为了方便多次测量,可以封装一个简单的计时器类:
#include <chrono>
#include <iostream>
<p>class Timer {
public:
Timer() { reset(); }</p><pre class='brush:php;toolbar:false;'>void reset() {
m_start = std::chrono::high_resolution_clock::now();
}
int64_t elapsedMicroseconds() const {
auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(end - m_start).count();
}
int64_t elapsedMilliseconds() const {
return elapsedMicroseconds() / 1000;
}private: std::chrono::time_point<std::chrono::high_resolution_clock> m_start; };
// 使用示例 int main() { Timer timer; for (int i = 0; i < 1000000; ++i) {} std::cout << "耗时: " << timer.elapsedMilliseconds() << " 毫秒" << std::endl; return 0; }
基本上就这些。日常开发中推荐使用 std::chrono,精度高、语义清晰、跨平台兼容性好。
以上就是c++++怎么计算程序运行时间_c++计算代码运行耗时的方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号