在测试程序执行所消耗的时间,一般用clock()函数,或者clock_gettime() 等获取开始和结束时间,如下
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int main(void)
{
clock_t start,end;
start =clock();
sleep(1);
end = clock();
printf("%f s\n",(double)(end-start)/CLOCKS_PER_SEC);
return 0;
}
按我一直的理解, sleep即让程序休眠1秒,然后在获取当前clock,然后求的时间是1s.
但是程序的结果如下:
zacha@Superman:code$ gcc timetest.c
zacha@Superman:code$ ./a.out
0.000031 s
zacha@Superman:code$ ./a.out
0.000035 s
zacha@Superman:code$ ./a.out
0.000032 s
zacha@Superman:code$
我想不明白、有哪位朋友解惑?
基本上搞清楚了:clock()函数有以下描述:
clock returns the processor time used by program since the beginning of the execution, or -1 if unavailable.
即:clock()函数返回的是程序运行过程中耗掉得process time,也就是CPU time。
那么这样理解就通了,sleep函数将进程挂起,而clock函数是获取CPU执行过程种消耗掉的的时间,由于进行没有执行,所以不存在CPU Time的消耗。即sleep不是表面上那么简单、