c中计时的几种方法

时间:2023-03-09 05:21:49
c中计时的几种方法

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