43 - clock()函数

1 函数原型

clock():用于获取程序运行的CPU时间,函数原型如下:

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.

2 参数

clock()函数的参数为void。

3 返回值

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

  1. 返回“从开启程序进程”到“程序中调用clock()函数”所经过的CPU时间(以clock tick为单位)。

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 示例

示例代码如下所示:

int main() {
   //
   clock_t start = 0;
   clock_t end = 0;
   double cpu_time_used = 0.0;
   // 
   start = clock();
   // 假设的耗时操作  
   for (long long i = 0; i < 1000000000; i++) {
   }
   //
   end = clock();
   //
   cpu_time_used = ((float)(end - start)) / CLOCKS_PER_SEC;
   //
   printf("CPU time used: %.3f seconds\n", cpu_time_used);
   //
   return 0;
}

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

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值