c中計時的幾種方法

來源:互聯網
上載者:User

標籤:

C計時的幾種方法說明及常式
1. 使用clock() 函數                                                

標頭檔:<time.h>

clock()函數,返回“自程式啟動到調用該函數,CPU時鐘的計時單元數(clock tick)”

每過1ms,計數值+1
精度:1毫秒
#include <stdio.h>
#include <time.h>

int main()
{
    clock_t start,end; // typedef long clock_t
    start = clock();
    long i= 1000000000L;while(i--){}
    end = clock();

    //#define CLOCKS_PER_SEC ((clock_t)1000)
    double duration =(double)(end-start)/CLOCKS_PER_SEC;
    printf("%f\n",duration); // 4.015

    return 0;
}
2. 使用time() 函數                                                  

標頭檔:<time.h> 中

clock()返回公元1970.01.01 0:0:0秒算起到現在所經過的秒數。

即Calendar Time,日曆時間

精度:1秒
#include <time.h>

int main()
{
    time_t start,end;  // typedef long time_t;
    start = time(NULL); // 等同於 time(&start);
    long i=1000000000L;while(i--){}
    end = time(NULL);

    long duration =end - start;
    printf("%ld\n",duration); // 4

    return 0;
}
3. 使用GetTickCount () 函數
標頭檔:<windows.h> 中
在精度要求較高的情況下,可以利用GetTickCount()函數,該函數的傳回值是  DWORD型,表示以ms為單位的電腦啟動後經曆的時間間隔(最大49.7天)。在較短的定時中其計時誤差為15ms,在較長的定時中其計時誤差較低,如果定時時間太長,就好象死機一樣,CPU佔用率非常高,只能用於要求不高的延時程式中。
精度:1毫秒,短時誤差15ms
#include <stdio.h>
#include <windows.h>

int main()
{
    DWORD start,end;//typedef unsigned long DWORD;
    start = GetTickCount();
    long i=1000000000L;while(i--){}
    end = GetTickCount();

    double duration = (double)(end-start)/1000;
    printf("%f\n",duration); // 3.922
    return 0;
}
4. 使用QueryFrequencyCount () 函數
標頭檔:<windows.h>
高精度計數器
精度:1微秒,誤差不超過0.5微妙(精度為1000 000/(cpu主頻)微秒)
#include <stdio.h>
#include <windows.h>

int main()
{
    LARGE_INTEGER f;
    QueryPerformanceFrequency(&f);//擷取內部高精度計數器的頻率

    double dFreq;
    dFreq = (double)f.QuadPart; //擷取計數器的頻率

    LARGE_INTEGER start,end;
    QueryPerformanceCounter(&start);//擷取內部高精度計數器當前的計數值
    long i=1000000000L;while(i--){}
    QueryPerformanceCounter(&end);

    //時間差 = 計數值差/頻率(單位s)
    double duration = (double)(end.QuadPart-start.QuadPart)/dFreq;
    printf("%f\n",duration);// 3.969499
    return 0;
}

 

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.