1. 程式人生 > >Windows/Linux高精度計時器(C++)

Windows/Linux高精度計時器(C++)

/* 
 * Linux/Windows 系統高精度計時器 
 */
  
#ifndef __LX_TIMER_H__  
#define __LX_TIMER_H__  
  
#ifdef WIN32  
    #include   
#elif linux  
    #include   
#endif  
  
class LxTimer  
{  
public:  
    LxTimer();  
    void   start();  
    double stop();   // 返回從 start 到 stop 所經歷的時間(單位:秒)  
  
private:  
#ifdef  WIN32  
    double dSystemFreq;   
    BOOL   flag;  
    double dStartTime;  
    double dStopTime;  
#elif  linux  
    struct timeval tvStart;  
    struct timeval tvStop;  
#endif  
};  
  
#endif

#include "LxTimer.h"  
  
#ifdef  WIN32  
    #include   
#elif  linux  
    #include   
#endif  
  
#ifdef WIN32  
LxTimer::LxTimer()  
{  
    LARGE_INTEGER sysFreq;  // 計時器頻率  
    flag = QueryPerformanceFrequency( &sysFreq );  
    if ( flag )  
    {  
        dSystemFreq = (double)sysFreq.QuadPart;  
    }  
}  
  
void LxTimer::start()  
{  
    LARGE_INTEGER t;  
    flag &= QueryPerformanceCounter( &t );  
    if ( !flag )  
        return;  
    dStartTime = (double)t.QuadPart;  
}  
  
double LxTimer::stop()  
{  
    LARGE_INTEGER t;  
    flag &= QueryPerformanceCounter( &t );  
  
    if ( !flag )  
        return -1.0;  
      
    dStopTime = (double)t.QuadPart;  
    return ( dStopTime - dStartTime ) / dSystemFreq;  
}  
  
#elif  linux  
  
LxTimer::LxTimer(){}  
  
void LxTimer::start()  
{  
    gettimeofday( &tvStart, NULL );  
}  
  
double LxTimer::stop()  
{  
    gettimeofday( &tvStop, NULL );  
    return (double)(tvStop.tv_sec - tvStart.tv_sec)  
        + (double)(tvStop.tv_usec - tvStart.tv_usec)/1000000.0;  
}  
  
#endif