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

目录

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

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

3、使用第三方库(如Boost.Timer)

4. 使用Windows API函数(Windows平台特有)


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;  
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草海桐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值