clock () -确定处理器时间
格式
#include <time.h>
clock_t clock(void);语言级别
ANSI
线程安全
是
描述
clock() 函数返回自实现定义的与进程调用相关的时间段开始以来程序所使用的处理器时间的近似值。 要获取时间 (以秒计) ,请将 clock() 返回的值除以宏 CLOCKS_PER_SEC的值。
返回值
如果处理器时间的值不可用或无法表示,那么 clock() 函数将返回值 (clock_t) -1。
要度量在程序中所花费的时间,请在程序开始时调用 clock() ,并从后续调用 clock()所返回的值中减去其返回值。 在其他平台上,您不能始终依赖于 clock() 函数,因为对 system() 函数的调用可能会重置时钟。
示例
此示例打印自调用程序以来经过的时间。
#include <time.h>
#include <stdio.h>
double time1, timedif; /* use doubles to show small values */
int main(void)
{
int i;
time1 = (double) clock(); /* get initial time */
time1 = time1 / CLOCKS_PER_SEC; /* in seconds */
/* running the FOR loop 10000 times */
for (i=0; i<10000; i++);
/* call clock a second time */
timedif = ( ((double) clock()) / CLOCKS_PER_SEC) - time1;
printf("The elapsed time is %lf seconds\n", timedif);
}