43 - clock()函数

文章目录

  • [1 函数原型](#1 函数原型)
  • [2 参数](#2 参数)
  • [3 返回值](#3 返回值)
  • [4 示例](#4 示例)

1 函数原型

clock():测量程序消耗的处理器时间,函数原型如下:

c 复制代码
clock_t clock (void);

ctime库描述如下:

复制代码
Clock program
1. Returns the processor time consumed by the program.
2. The value returned is expressed in clock ticks, which are units of time of a constant but system-specific length (with a relation of CLOCKS_PER_SEC clock ticks per second).
3. The epoch used as reference by clock varies between systems, but it is related to the program execution (generally its launch). 
4. To calculate the actual processing time of a program, the value returned by clock shall be compared to a value returned by a previous call to the same function.
  1. clock()函数功能:用于测量程序执行过程中消耗的处理器时间,以时钟滴答(clock ticks)为单位;时钟滴答是一种长度恒定但系统特定的时间单位,具体长度可能在不同的系统中有所不同,与CLOCKS_PER_SEC相关;
  2. 处理器时间:CPU实际用于执行程序的时间,而不是程序在等待输入或其他操作时的时间;
  3. 时钟滴答:每个系统都有自己的时钟频率,CLOCKS_PER_SEC表示每秒钟有多少个时钟滴答;将时钟滴答数除以CLOCKS_PER_SEC,可以将时钟滴答转换为秒;
  4. 时间参考点:clock()函数的返回值是从程序启动到当前时刻的时钟滴答数,不同系统的起始点可能不同,但通常是程序运行的开始;
  5. 比较调用:要获取程序的实际运行时间,需要在程序的不同阶段调用clock()函数并比较它们的返回值,这样可以得出在这些调用之间消耗的处理器时间。

2 参数

clock()函数的参数为void。

3 返回值

clock()函数返回值类型为clock_t类型:

  1. 返回从程序启动到调用clock()函数所经过的处理器时间,单位为时钟滴答。

ctime库描述如下:

复制代码
Return Value
1. The number of clock ticks elapsed since an epoch related to the particular program execution.
2. On failure, the function returns a value of -1.
3. clock_t is a type defined in <ctime> as an alias of a fundamental arithmetic type.

4 示例

示例代码如下所示:

c 复制代码
int main() {
   //
   clock_t start = 0;
   clock_t end = 0;
   double cpu_time_used = 0.0;
   // 
   start = clock();

   printf("大循环开始前 : %ld\n", start);
   // 假设的耗时操作  
   for (long long i = 0; i < 1000000000; i++) {
   }
   //
   end = clock();

   printf("大循环结束后 : %ld\n", end);
   //
   cpu_time_used = ((float)(end - start)) / CLOCKS_PER_SEC;
   //
   printf("大循环消耗的CPU时间 : %.3f seconds\n", cpu_time_used);
   //
   return 0;
}

代码运行结果如下图所示:

相关推荐
SunnyKriSmile1 小时前
输入10个数并求最大值
c语言·算法
No0d1es11 小时前
电子学会青少年软件编程(C/C++)5级等级考试真题试卷(2024年6月)
c语言·c++·算法·青少年编程·电子学会·五级
Peter_Deng.15 小时前
Linux 下基于 TCP 的 C 语言客户端/服务器通信详解(三个示例逐步进阶)
服务器·c语言·网络
John.Lewis17 小时前
数据结构初阶(13)排序算法-选择排序(选择排序、堆排序)(动图演示)
c语言·数据结构·排序算法
丑小鸭是白天鹅20 小时前
嵌入式C语言学习笔记之枚举、联合体
c语言·笔记·学习
GUET_一路向前21 小时前
【C语言防御性编程】if条件常量在前,变量在后
c语言·开发语言·if-else·防御性编程
pusue_the_sun1 天前
数据结构——栈和队列oj练习
c语言·数据结构·算法··队列
Dontla1 天前
Makefile介绍(Makefile教程)(C/C++编译构建、自动化构建工具)
c语言·c++·自动化
奶黄小甜包1 天前
C语言零基础第18讲:自定义类型—结构体
c语言·数据结构·笔记·学习
一支闲人1 天前
C语言相关简单数据结构:双向链表
c语言·数据结构·链表·基础知识·适用于新手小白