【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
$
本文介绍了如何在C/C++中利用`clock()`函数从`time.h`库获取程序的执行时间。通过在代码的特定位置调用`clock()`,可以计算程序运行的总时间,包括用户时间和系统时间。示例代码展示了在for循环前后使用`clock()`来计算时间差,并使用`CLOCKS_PER_SEC`常量将结果转换为秒。

被折叠的 条评论
为什么被折叠?



