[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++函数耗时计算

相关推荐
To_OC7 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
炸膛坦客8 小时前
单片机/C/C++八股:(二十六)IIC 专题(I²C)---- 上集
c语言·c++·单片机
旖-旎8 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
灯澜忆梦9 小时前
GO_并发编程---定时器
开发语言·后端·golang
-银雾鸢尾-9 小时前
C#中的StringBuilder相关方法
开发语言·c#
To_OC9 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
Henry Zhu1239 小时前
C++中的特殊成员函数与智能指针
c++
-银雾鸢尾-9 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
delishcomcn10 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹10 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试