1. 程式人生 > >C語言 time.h中clock()函式 和 time()函式的使用

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;
}