当前位置: 首页 > news >正文

[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(); // 结束计时// 打印程序耗时,单位:秒sstd::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 thingfor (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++函数耗时计算

http://www.lryc.cn/news/309666.html

相关文章:

  • Redis是单线程还是多线程?
  • 【MySQL】MySQL数据管理——DDL数据操作语言(数据表)
  • Qt使用QSettings类来读写ini
  • 嵌入式软件bug从哪里来,到哪里去
  • 去掉WordPress网页图片默认链接功能
  • UE学习笔记--解决滚轮无法放大蓝图、Panel等
  • GO结构体
  • 芯科科技为全球首批原生支持Matter-over-Thread的智能锁提供强大助力,推动Matter加速成为主流技术
  • 面试数据库篇(mysql)- 06覆盖索引
  • [伴学笔记]01-操作系统概述 [南京大学2024操作系统]
  • c++二叉树
  • 第19章-IPv6基础
  • 浅谈人才招聘APP开发的解决方案
  • 大语言模型LLM推理加速:Hugging Face Transformers优化LLM推理技术(LLM系列12)
  • JVM 第四部分—垃圾回收相关概念 2
  • tritonserver学习之八:redis_caches实践
  • 2024有哪些免费的mac苹果电脑深度清理工具?CleanMyMac X
  • UE5中实现后处理深度描边
  • Java面试值之集合
  • React之组件定义和事件处理
  • LeetCode -55 跳跃游戏
  • Android和Linux的嵌入式开发差异
  • 关于Node.js异常处理的教程
  • 13. Springboot集成Protobuf
  • Spring: Springboot 框架集成不同版本的spring redis
  • 学习JAVA的第八天(基础)
  • 【硬件相关】IB网/以太网基础介绍及部署实践
  • 【JavaEE】_Spring MVC项目之建立连接
  • 【JavaEE进阶】 Spring AOP源码简单剖析
  • Redis--内存回收机制详解