[C++] 统计程序耗时

一、简介

本文介绍了两种在C++代码中统计耗时的方法,第一种使用<time.h>头文件中的clock()函数记录时间戳,统计程序耗时。第二种使用<chrono>头文件中的std::chrono::high_resolution_clock()::now()函数,后者可以方便地统计不同时间单位下的程序耗时,例如秒(s)、毫秒(ms)、微秒(μs)或者纳秒(ns)。

二、代码示例

1. 使用<time.h>头文件中的clock()函数统计耗时

cpp 复制代码
#include <iostream>
#include <time.h>
#include <math.h>
int main(int, char **)
{
    clock_t start;
    clock_t finish;
    start = clock(); // 开始计时
    /* do some thing */
    for (int i = 0; i < 10000; i++)
    {
        float c = exp(2.0);
    }
    finish = clock(); // 结束计时
    // 打印程序耗时,单位:秒s
    std::cout << (double)(finish - start) / CLOCKS_PER_SEC << std::endl;
}

2. 使用 <chrono>头文件中的std::chrono::high_resolution_clock::now()函数统计耗时

cpp 复制代码
#include <iostream>
#include <math.h>
#include <chrono>

int main(int, char **)
{
    std::chrono::high_resolution_clock::time_point start;
    std::chrono::high_resolution_clock::time_point finish;

    start = std::chrono::high_resolution_clock::now(); // 开始计时

    // do some thing
    for (int i = 0; i < 10000; i++)
    {
        float c = exp(2.0);
    }

    finish = std::chrono::high_resolution_clock::now(); // 结束计时

    // 打印程序耗时
    std::cout << "耗时为:" << std::chrono::duration_cast<std::chrono::seconds>(finish - start).count() << "s.\n";
    std::cout << "耗时为:" << std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count() << "ms.\n";
    std::cout << "耗时为:" << std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count() << "us.\n";
    std::cout << "耗时为:" << std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count() << "ns.\n";
    return 0;
}

三、参考

1\].[C++函数耗时计算](https://blog.csdn.net/dally2/article/details/125668097)

相关推荐
明月醉窗台4 分钟前
qt使用笔记六之 Qt Creator、Qt Widgets、Qt Quick 详细解析
开发语言·笔记·qt
wangjialelele7 分钟前
平衡二叉搜索树:AVL树和红黑树
java·c语言·开发语言·数据结构·c++·算法·深度优先
苏宸啊9 分钟前
C++栈和队列
c++
lili-felicity15 分钟前
CANN性能调优与实战问题排查:从基础优化到排障工具落地
开发语言·人工智能
独自破碎E17 分钟前
【BISHI15】小红的夹吃棋
android·java·开发语言
森G19 分钟前
七、04ledc-sdk--------makefile有变化
linux·c语言·arm开发·c++·ubuntu
驱动探索者24 分钟前
linux mailbox 学习
linux·学习·算法
ringking12327 分钟前
autoware-1:安装环境cuda/cudnn/tensorRT库函数的判断
人工智能·算法·机器学习
进阶小白猿30 分钟前
Java技术八股学习Day33
java·开发语言·学习
大闲在人1 小时前
8. 供应链与制造过程术语:产能
算法·制造·供应链管理·智能制造·工业工程