栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

前言

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

方法(推荐方法4) 1(返回的是CPU时钟计时单元,每秒为1000个时钟周期)(单位为s,可精确到小数点后三位)
#include    // or  #include 
const clock_t begin_time = clock();    
float seconds = float(clock( ) - begin_time) / 1000;    //最小精度到ms
2 (单位为ms,仅精确到整数部分
#include 
#include 
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(endTime - beginTime);
    std::cout << timeInterval.count() << "msn";
}
3 (单位为ms,仅精确到整数部分
#include 
#include      //解决DWORD报错

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

DWORD time = end1 - start1;
cout << "所耗时间为:" << time << "ms" << endl;
4 (单位为s,可精确到小数点后七位)
#include    //计算时间
using namespace std::chrono;

auto starttime = system_clock::now();
...
duration diff = system_clock::now()- starttime;
cout << "所耗时间为:" << diff.count() << "s" << endl;

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847663.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号