本文最后更新于:2024年1月14日 晚上

C++ 中计时是度量系统性能的常用方法,本文记录 C++ 常用计时方法。

time.h

time.h 是最常用的 C++ 计时头文件,在 C++ 中,计时通常使用 <time.h> 头文件中的 clock() 函数记录CPU 单元的运行周期时间,可以在 Windows / Linux 等操作系统中使用,配合 CLOCKS_PER_SEC 实现对真实事件单位秒(s)等的转换。

  • 两次调用 clock() 函数,差值表示程序运行开始和结束时刻之间的CPU时钟计时单元(clock tick)数;
  • CLOCKS_PER_SEC,表示一秒钟会有多少个时钟计时单元(clock tick);
  • 设差值为 durationduration / CLOCKS_PER_SEC 就为秒。

数据类型

计时得到的常用数据类型是 clock_ttime_t, 在 time.h 文件中,我们可以找到对它们的定义:

  • clock_t
1
2
3
4
5
6
7
#ifndef _CLOCK_T_DEFINED 

  typedef long clock_t;

  #define _CLOCK_T_DEFINED

  #endif

说明 clock_t 类型本质就是 long 类型

  • time_t
1
2
3
4
5
6
7
8
9
10
typedef long                          __time32_t;
typedef __int64 __time64_t;

#ifndef _CRT_NO_TIME_T
#ifdef _USE_32BIT_TIME_T
typedef __time32_t time_t;
#else
typedef __time64_t time_t;
#endif
#endif

说明 time_t 可能是 32 位整形或 64 位整形

  • 总之时间本质就是一个大整形数据

计时间隔

一个 clock 表示一个计时间隔,每经过一个计时间隔的时间这个计时的整数会增加 1

计时间隔 和真实时间的联系靠的是 CLOCKS_PER_SEC,这个宏的含义是一秒钟有多少个计时间隔

在定义中 CLOCKS_PER_SEC 是 1000

1
#define CLOCKS_PER_SEC  ((clock_t)1000)

也就表示一个 计时间隔 表示 1ms 的时间

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>

using namespace std;


int main(void)
{
long i = 100000000L;
time_t start, finish;
double duration;
/* 测量一个事件持续的时间*/
printf("Time to do %ld empty loops is ", i);
start = clock();
while (i--)
;
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("%f seconds\n", duration);
return 0;
}

输出

1
Time to do 100000000 empty loops is 0.148000 seconds

参考资料



文章链接:
https://www.zywvvd.com/notes/coding/cpp/cpp-timer/cpp-timer/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

C++ 计时
https://www.zywvvd.com/notes/coding/cpp/cpp-timer/cpp-timer/
作者
Yiwei Zhang
发布于
2023年3月22日
许可协议