C语言 time.h中clock()函数 和 time()函数的使用

NAME
       clock - determine processor time //处理器时间处理

SYNOPSIS
       #include <time.h>

       clock_t clock(void);

DESCRIPTION
       The clock() function returns an approximation of processor time used by the program.

       //clock()函数返回程序所使用的处理器时间近似值

RETURN VALUE
       The value returned is the CPU time used so far as a clock_t; to get the number of seconds used, divide by
       CLOCKS_PER_SEC.  If the processor time used is not available or its  value  cannot  be  represented,  the
       function returns the value (clock_t) -1.

       //返回值是clock_t类型的CPU 时间,除以CLOCKS_PER_SEC得到秒值。

 The C standard allows for arbitrary values at the start of the program; subtract the value returned  from
       a call to clock() at the start of the program to get maximum portability.

       Note that the time can wrap around.  On a 32-bit system where CLOCKS_PER_SEC equals 1000000 this function
       will return the same value approximately every 72 minutes.

       On several other implementations, the value returned by clock() also includes the times of  any  children
       whose  status  has  been  collected  via wait(2) (or another wait-type call).  Linux does not include the
       times of waited-for children in the value returned by clock().  The times(2) function,  which  explicitly
       returns (separate) information about the caller and its children, may be preferable.

       In  glibc  2.17  and  earlier,  clock() was implemented on top of times(2).  For improved accuracy, since
       glibc 2.18, it is implemented on top of clock_gettime(2) (using the CLOCK_PROCESS_CPUTIME_ID clock).

C语言中求程序执行的时间可以使用clock()函数
这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,其中clock_t是用来保存时间的数据类型,很明显,clock_t是一个长整形数,常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,
下面给出一个示例:

#include <time.h>
#include <stdio.h>
#include <unistd.h>
int fibcount = 0;
int fib(int n){
    fibcount++;
    if(n == 0) return 0;
    if(n == 1) return 1;
    return fib(n-1) + fib(n-2);
}

int main(){
    int n = 40;
    time_t t1,t2;
    time_t startTime = clock();
    time(&t1);
    int res =fib(n);
    time(&t2);
    time_t endTime = clock();

    printf("fib is %d 。",res);
    printf("time start,end is %f\n",difftime(endTime,startTime)/CLOCKS_PER_SEC);
    printf("time t1 t2 is %f\n",difftime(t2,t1));
    printf("fib count is %d\n",fibcount);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/phoenixcsl/article/details/84619813
今日推荐