有时候在实际应用中要计算一个事件持续的时间长度,比如计算打字速度。在第1节计时部分中,我已经用clock函数举了一个例子。Clock()函数可以精确到毫秒级。同时,我们也可以使用difftime()函数,但它只能精确到秒。该函数的定义如下:
double difftime(time_t time1, time_t time0);
虽然该函数返回的以秒计算的时间间隔是double类型的,但这并不说明该时间具有同double一样的精确度,这是由它的参数觉得的(time_t是以秒为单位计算的)。比如下面一段程序:
#include
<time.h> #include
<stdio.h> #include
<stdlib.h> int main( void ) { time_t start,end; start
= time (NULL); system ( "pause" ); end
= time (NULL); printf ( "The
pause used %f seconds.\n" ,
difftime (end,start)); system ( "pause" ); return 0; } |
运行结果为:
请按任意键继续. . .
The pause used 2.000000 seconds.
请按任意键继续. . .
可以想像,暂停的时间并不那么巧是整整2秒钟。其实,你将上面程序的带有“//<-”注释的一行用下面的一行代码替换:
printf("The pause used %f seconds./n",end-start);
其运行结果是一样的。