it编程 > 编程语言 > C/C++

C++记录程序运行时间的四种方法

60人参与 2025-03-17 C/C++

1. 使用 <chrono> 库(c++11及以后版本)

<chrono> 库提供了高精度的时间测量功能。

#include <iostream>  
#include <chrono>  
  
int main() {  
    auto start = std::chrono::high_resolution_clock::now();  
  
    // your code here  
    // ...  
  
    auto stop = std::chrono::high_resolution_clock::now();  
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count();  
  
    std::cout << "elapsed time: " << duration << " ms\n";  
  
    return 0;  
}

2. 使用 <ctime> 库(较旧但常用的方法)

<ctime> 库提供了基于系统时间的函数clock()。

#include <iostream>  
#include <ctime>  
  
int main() {  
    clock_t start = clock(); //也可以double start = clock(); 
  
    // your code here  
    // ...  
  
    clock_t end = clock();  
    double cpu_time_used = static_cast<double>(end - start) / clocks_per_sec;
    //  /clocks_per_sec将结果转为以秒为单位
  
    std::cout << "cpu time used: " << cpu_time_used << " s\n";  
  
    return 0;  
}

3、使用第三方库(如boost.timer)

boost库提供了一个计时器模块,用于测量代码块的执行时间。

首先,你需要安装 boost库,并在项目中包含boost.timer头文件。

#include <boost/timer/timer.hpp>  
#include <iostream>  
  
int main() {  
    boost::timer::auto_cpu_timer t; // 自动测量和打印执行时间  
  
    // your code here  
    // ...  
  
    return 0;  
}

4. 使用windows api函数(windows平台特有)

4.1 使用 gettickcount()

这个函数返回从系统启动开始经过的毫秒数。gettickcount() 的精度在1到15毫秒之间,并且其值会在大约49.7天后回绕。

#include <windows.h>  
#include <iostream>  
  
int main() {  
    dword start = gettickcount();  
    // ... 执行你的代码 ...  
    dword end = gettickcount();  
    std::cout << "程序运行时间: " << (end - start) << " 毫秒" << std::endl;  
    return 0;  
}

4.2 使用 queryperformancecounter() 和 queryperformancefrequency()

这两个函数提供了更高的精度,通常在微秒级别。

#include <windows.h>  
#include <iostream>  
  
int main() {  
    large_integer start, end, freq;  
    queryperformancefrequency(&freq);  
    queryperformancecounter(&start);  
    // ... 执行你的代码 ...  
    queryperformancecounter(&end);  
    double elapsedtime = (double)(end.quadpart - start.quadpart) / freq.quadpart * 1000.0; // 毫秒  
    std::cout << "程序运行时间: " << elapsedtime << " 毫秒" << std::endl;  
    return 0;  
}

到此这篇关于c++记录程序运行时间的四种方法的文章就介绍到这了,更多相关c++程序运行时间内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

C/C++随机数生成的五种方法

03-17

VSCode中C/C++编码乱码问题的两种解决方法

03-17

QT移植到RK3568开发板的方法步骤

03-16

Qt 智能指针的具体使用

03-16

Qt把文件夹从A移动到B的实现示例

03-16

C++数组去重十种方法

03-16

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论