[C++] 统计程序耗时

一、简介

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

二、代码示例

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

#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()函数统计耗时

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

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值