高精度计时

Windows

①计时统计前先调用QueryPerformanceFrequency()函数获得机器内部计时器的时钟频率。
②在需要计时的事件发生前和发生之后分别QueryPerformanceCounter(),利用两次获得的计数之差和时钟频率,就可以计算出事件经历的精确时间(精度可以达到微秒级别)。

#include   
#include   

int main()
{
    LARGE_INTEGER timeStart;    //开始时间  
    LARGE_INTEGER timeEnd;      //结束时间  

    LARGE_INTEGER frequency;    //计时器频率  
    QueryPerformanceFrequency(&frequency);
    double quadpart = (double)frequency.QuadPart;//计时器频率  

    QueryPerformanceCounter(&timeStart);
    Sleep(1000);//延时一秒  
    QueryPerformanceCounter(&timeEnd);

    //得到两个时间的耗时  
    double elapsed1= (timeEnd.QuadPart - timeStart.QuadPart) / quadpart;
    std::cout << elapsed1 <<"s"<< std::endl;//单位为秒,精度为微秒(1000000/cpu主频)  
    double elapsed2 = (timeEnd.QuadPart - timeStart.QuadPart)*1000 / quadpart;
    std::cout << elapsed2 <<"ms"<< std::endl;//单位为秒,精度为微秒(1000000/cpu主频)  
    system("pause");
    return 0;
}

Linux

struct  timeval{
       long  tv_sec;/*秒*/
       long  tv_usec;/*微妙*/

};

#include 
#include 

int main() {
    struct timeval start, end;
    gettimeofday( &start, NULL );
    sleep(3);
    gettimeofday( &end, NULL );
    int timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec -start.tv_usec;
    printf("time: %d 微秒\n", timeuse);
    return 0;
}

gettimeofday能得到微秒数,比毫秒还要更精确。

你可能感兴趣的:(高精度计时)