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

相关推荐
Sakura_j_h_17 分钟前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
微笑星河q25 分钟前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
Eider19981 小时前
Python基础语法之并发相关3
开发语言·python
FRing031 小时前
vue2干货总结11(短信验证、登录功能、统一处理错误(响应拦截器)、将token信息存入vuex、vuex持久化处理)
开发语言·前端·javascript·vue.js·vue2
CS_Zero2 小时前
DeepSeek V4.1 Flash 1017 (Batch) 新手极速上手指南
开发语言·batch·deepseek
山楂树の2 小时前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言
Risehuxyc2 小时前
C# 发展历史
开发语言·c#
HaiXCoder3 小时前
C++ 表达式怎么读:从一行代码到类型、值类别和生命周期
c++
武子康3 小时前
H3-World 扩展跳跃与开门:新动作怎样进入训练数据?
大数据·人工智能·算法
卡尔曼的BD SLAMer3 小时前
北斗导航 |GNSS ION论文集汇总1997到2022(链接在文末)
算法·北斗导航