[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)

相关推荐
catchadmin1 分钟前
成为高级 PHP 开发者需要的思维转变
开发语言·php
请告诉他2 分钟前
从 Struts2 单体到 Spring Cloud 微服务:一个 P2P 系统的真实重构之路(2019 年实战复盘)
java·开发语言
睡醒了叭4 分钟前
图像分割-传统算法-聚类算法
opencv·算法·计算机视觉·聚类
雾岛听蓝5 分钟前
C++ string 类解析
开发语言·c++
这周也會开心5 分钟前
Java面试题2-集合+数据结构
java·开发语言·数据结构
子枫秋月6 分钟前
模拟C++string实现
数据结构·c++·算法
~央千澈~7 分钟前
人工智能AI算法推荐之番茄算法推荐证实其算法推荐规则技术解析·卓伊凡
人工智能·算法·机器学习
oioihoii7 分钟前
C++内存安全方案前沿研究
c++·安全·mfc
羚羊角uou8 分钟前
【数据结构】常见排序
数据结构·算法·排序算法
十五年专注C++开发9 分钟前
QProcess在Windows下不能正常启动exe的原因分析
开发语言·c++·windows·qprocess·createprocess