C/C++下測量函數已耗用時間

來源:互聯網
上載者:User

標籤:測試   儲存時間   之間   寫法   markdown   blog   main   結果   編譯   

C/C++下測量函數已耗用時間time.h介紹

C/C++中的計時函數是clock(),而與其相關的資料類型是clock_t。

clock_t clock( void );

這個函數返回從“開啟這個程式進程”到“程式中調用clock()函數”時之間的CPU時鐘計時單元(clock tick)數,稱之為掛鐘時間(wal-clock)。其中clock_t是用來儲存時間的資料類型,在time.h檔案中,我們可以找到對它的定義:

#ifndef _CLOCK_T_DEFINED  typedef long clock_t; #define _CLOCK_T_DEFINED #endif

很明顯,clock_t是一個長整形數。在time.h檔案中,還定義了一個常量CLOCKS_PER_SEC,它用來表示一秒鐘會有多少個時鐘計時單元,其定義如下:

#define CLOCKS_PER_SEC ((clock_t)1000) //CLOCKS_PER_SEC為系統自訂的

可以看到每過千分之一秒(1毫秒),調用clock()函數返回的值就加1。

寫法
#include<stdio.h>#include<time.h>int main(){  clock_t cBeg=clock();  //···  //調用函數  //···  clock_t cEnd=clock();  printf("program exection time: %.3f\n",(double)(cEnd-cBeg)/CLOCK_PER_SEC);  return 0;}
例子
#include<stdio.h>#include<time.h>//直接遞迴long long fib1(int n){    if(n==1||n==0)        return 1;    else        return fib1(n-1)+fib1(n-2);}//尾遞迴long long fib2(int n,long long f,long long s){    if(n<2)        return s;    else        return fib2(n-1,s,f+s);}//迭代long long fib3(int n){    long long f=1;    long long g=0;    while(n--)    {        f=f+g;        g=f-g;    }    return f;}int main(){    clock_t tBeg,tEnd;    tBeg=clock();    printf("%lld\n",fib1(40));    tEnd=clock();    printf("fib1 execution time: %.3f s\n",(double)(tEnd-tBeg)/CLOCKS_PER_SEC);    tBeg=clock();    printf("%lld\n",fib2(40,1,1));    tEnd=clock();    printf("fib1 execution time: %.3f s\n",(double)(tEnd-tBeg)/CLOCKS_PER_SEC);    tBeg=clock();    printf("%lld\n",fib3(40));    tEnd=clock();    printf("fib1 execution time: %.3f s\n",(double)(tEnd-tBeg)/CLOCKS_PER_SEC);}

執行結果如下:

(尾遞迴由於編譯器最佳化和迭代比直接遞迴快很多)

另外,linux下可直接 time ./執行程式測試時間。

C/C++下測量函數已耗用時間

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.