高精度计时器(High Resolution Timer)

原文地址:http://www.songho.ca/misc/timer/timer.html


一、C计时器


C语言标准库里提供了clock()函数来测量代码执行时间,包含在#include<time.h>头文件中。该函数和系统平台相互独立,支持多种系统运行,但精度不高,甚至达不到毫秒的精度。


可以使用下面的代码测试clock()的精度。输出结果即是函数clock()可以测量的最小时间差(不同的系统可能得到的结果不同,博主分别在ubuntu和windows系统测量的最小时间差为1ms和15ms)。

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
    clock_t t1, t2;
    t1 = t2 = clock();

    // loop until t2 gets a different value
    while(t1 == t2)
        t2 = clock();

    // print resolution of clock()
    cout << (double)(t2 - t1) / CLOCKS_PER_SEC * 1000 << " ms.\n";

    return 0;
}

因此,需要一个精度至少为1ms的计时器来测量时间。好消息是已经有更高精度的计时器,但坏消息是这些函数并不能跨平台使用。换句话说,就是在不同的系统上必须编写不同的代码。Windows提供了QueryPerformanceCounter()函数,而Unix、Linux以及Mac系统则使用gettimeofday()函数(该函数包含在#include<sys/time.h>头文件中)。这两个函数均可以达到至少1ms的测量时间精度。


二、Windows


Windows API提供了精度非常高的时间函数,QueryPerformanceCounter()函数和QueryPerformanceFrequency()函数。QueryPerformanceCounter()函数用来获取当前的时间ticks,QueryPerformanceFrequency()函数则用来获得每秒的ticks数,通过这两个函数就可以将ticks转化成实际的时间。

下面代码给出了QueryPerformanceCounter()函数的使用方法。


#include <iostream>
#include <windows.h>                // for Windows APIs
using namespace std;

int main()
{
    LARGE_INTEGER frequency;        // ticks per second
    LARGE_INTEGER t1, t2;           // ticks
    double elapsedTime;

    // get ticks per second
    QueryPerformanceFrequency(&frequency);

    // start timer
    QueryPerformanceCounter(&t1);

    // do something
    ...

    // stop timer
    QueryPerformanceCounter(&t2);

    // compute and print the elapsed time in millisec
    elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
    cout << elapsedTime << " ms.\n";

    return 0;
}

三、Unix、Linux和Mac


gettimeofday()函数被用在Unix、Linux和Mac系统上测量时间,包含在头文件#include<sys/time.h>中。该函数的测量精度同样为1ms。下面给出代码示例。


#include <iostream>
#include <sys/time.h>                // for gettimeofday()
using namespace std;

int main()
{
    timeval t1, t2;
    double elapsedTime;

    // start timer
    gettimeofday(&t1, NULL);

    // do something
    ...

    // stop timer
    gettimeofday(&t2, NULL);

    // compute and print the elapsed time in millisec
    elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
    cout << elapsedTime << " ms.\n";

    return 0;
}


四、C++ Timer Class


该timer类同时包含了QueryPerformanceCounter()函数和gettimeofday()函数,因此可以在Windows和Unix/Linux/Mac系统上使用。同时,它提供了简易的接口可以轻松获取代码执行时间。

源代码可以从这里下载:timer.zip


下面给出基本的使用示例。


#include <iostream>
#include "Timer.h"
using namespace std;

int main()
{
    Timer timer;

    // start timer
    timer.start();

    // do something
    ...

    // stop timer
    timer.stop();

    // print the elapsed time in millisec
    cout << timer.getElapsedTimeInMilliSec() << " ms.\n";

    return 0;
}

猜你喜欢

转载自blog.csdn.net/lsq2902101015/article/details/51066193
今日推荐