C++计算耗时方法(四种方法)

前言

本博客将给出四种在 C++ 中可用于 计算算法耗时 的方法。

方法(推荐方法4

1(返回的是CPU时钟计时单元,每秒为1000个时钟周期)(单位为s,可精确到小数点后三位)

#include <time.h>   // or  #include <ctime>
const clock_t begin_time = clock();    
float seconds = float(clock( ) - begin_time) / 1000;    //最小精度到ms

2 (单位为ms,仅精确到整数部分

#include <iostream>
#include <chrono>
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;

int main()
{
    high_resolution_clock::time_point beginTime = high_resolution_clock::now();
    ...
    high_resolution_clock::time_point endTime = high_resolution_clock::now();
    milliseconds timeInterval = std::chrono::duration_cast<milliseconds>(endTime - beginTime);
    std::cout << timeInterval.count() << "ms\n";
}

3 (单位为ms,仅精确到整数部分

#include <sys/timeb.h>
#include <Windows.h>     //解决DWORD报错

DWORD start1, end1;      
start1 = GetTickCount();
end1 = GetTickCount(); 

DWORD time = end1 - start1;
cout << "所耗时间为:" << time << "ms" << endl;

4 (单位可到微秒)

#include <chrono>   //计算时间
using namespace std::chrono;

auto starttime = system_clock::now();
...
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(system_clock::now()- starttime).count();
cout << "所耗时间为:" << diff << "ms" << endl;

在这里插入图片描述


彩蛋:
python计算程序耗时:(单位为s)

import time
starttime = time.time()   # 记录当前时间,返回当前时间的时间戳(1970纪元后经过的浮点秒数)
.......
endtime = time.time()
time = endtime - starttime
print(f"所耗时间为{time}s")

------tbc-------
有用可以点个大拇指哦 🤭

  • 12
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

8倍

谢谢大佬~

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

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

打赏作者

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

抵扣说明:

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

余额充值