计时函数
- 在C++中,计时通常使用
<time.h>
头文件中的clock()
函数记录CPU单元的运行周期时间,配合CLOCKS_PER_SEC
实现对真实事件单位秒(s)等的转换。- 两次调用
clock()
函数,差值表示程序运行开始和结束时刻之间的CPU时钟计时单元(clock tick)数; CLOCKS_PER_SEC
,表示一秒钟会有多少个时钟计时单元(clock tick);- 设差值为
duration
,duration / CLOCKS_PER_SEC
就为秒。
- 两次调用
计时程序
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
double duration;
/* 测量一个事件持续的时间*/
start = clock();
// do something...
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("%f seconds\n", duration);
return 0;
}