首页 > 代码库 > 计时器

计时器

Timer.h

#ifndef __LX_TIMER_H__  #define __LX_TIMER_H__    #ifdef WIN32      #include <Windows.h>  #elif linux      #include <sys/time.h>  #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

 

Timer.cpp

 

#include "stdafx.h"#include "timer.h"   #ifdef  WIN32  #include <Windows.h>  #elif  linux  #include <sys/time.h>  #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

 

计时器