【C/C++时间系列】通过clock()函数获取程序执行时间

本文介绍了如何在C/C++中利用`clock()`函数从`time.h`库获取程序的执行时间。通过在代码的特定位置调用`clock()`,可以计算程序运行的总时间,包括用户时间和系统时间。示例代码展示了在for循环前后使用`clock()`来计算时间差,并使用`CLOCKS_PER_SEC`常量将结果转换为秒。
摘要由CSDN通过智能技术生成

【clock()】

函数原型定义在time.h中,如下

程序到目前为止所使用的时间(用户时间+系统时间)。
结果/时钟_秒是程序时间(以秒为单位)

 /* Time used by the program so far (user time + system time).
    The result / CLOCKS_PER_SECOND is program time in seconds.  */
 extern clock_t clock (void) __THROW;

代码示例:

#include <iostream>
#include <time.h>
using namespace std;
int main()
{
   clock_t  begin ,end;
   begin=clock();
   for(int i=0;i<10000;i++)
   {
       for(int j=0;j<10000;j++)
       {}
   }
   end=clock();
   cout<<"sizeof(clock_t) is:"<<sizeof(clock_t)<<endl;
   cout<<"time used:"<< (double)(end - begin) / CLOCKS_PER_SEC << endl;

   cout<<"begin is:"<<begin<<endl;
   cout<<"end  is:"<<end<<endl;
   cout<<"CLOCKS_PER_SEC is:"<<CLOCKS_PER_SEC<<endl;
}
~                                            

在for循环前后执行clock() 来获取时间单元(实际情况应该是从main 开始)

通过sizeof 查看clock_t的大小

通过double类型转换查看程序执行的时间,单位秒

打印常量CLOCKS_PER_SEC。

执行结果如下

$
$gcc -lstdc++ l_clock.cpp 
$./a.out 
sizeof(clock_t) is:8
time used:0.18
begin is:0
end  is:180000
CLOCKS_PER_SEC is:1000000
$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值