【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
$