參考:http://blog.xuite.net/porpoise/blog/23589563

code http://damody.googlecode.com/files/testtime.7z

效能比:
我的電腦 vista x64 4核心 2.8Ghz
release下
rdtsc 一秒可執行
19452589 次

QueryPerformanceCounter  一秒可執行
854023 次

.h

#ifndef _RDTSCTIMER_
#define _RDTSCTIMER_
#include <windows.h>

class rdtscTimer
{
public:
 enum TimerState
 {
  RUNNING,
  STOPPED,
 };
 double m_fTime;
 TimerState m_eState;
 unsigned __int64 m_start_tick;
 unsigned __int64 m_end_tick;
private:
 inline unsigned __int64 rdtsc(void) {
  //__asm cpuid;
  __asm rdtsc;
 }
 static double second_per_tick;
public:
 rdtscTimer();
 double Start();
 double Stop();
 void  Restart()
 {
  m_eState = RUNNING;
  m_start_tick = rdtsc();
  m_fTime = 0;
 }
 inline void ReTick() { m_start_tick = rdtsc(); }
 inline double GetTime_Second()
 {
  m_end_tick = rdtsc();
  return double(m_end_tick-m_start_tick)/second_per_tick;
 }
 inline double GetTime_MS() { return GetTime_Second() * 1000.0; }
 inline double GetTime() { return GetTime_Second(); }

};

#endif // _RDTSCTIMER_

.cpp

#include "rdtscTimer.h"
#include <intrin.h>

double rdtscTimer::second_per_tick = 0;

rdtscTimer::rdtscTimer(void)
{
 if (second_per_tick == 0)
 {
  LARGE_INTEGER pstart, pend, counter_frequency;
  QueryPerformanceFrequency(&counter_frequency);
  QueryPerformanceCounter(&pstart);
  unsigned __int64 start = rdtsc();
  double time_diff = 0.0, frequency = (double)counter_frequency.QuadPart;
  for (;time_diff<1.0;)
  {
   QueryPerformanceCounter(&pend);
   __int64 iend = pend.QuadPart - pstart.QuadPart;
   time_diff = (double) iend / frequency;
  }
  unsigned __int64 end = rdtsc();
  second_per_tick = double(end - start);
 }
}

double rdtscTimer::Start(void)
{
 m_eState = RUNNING;
 m_start_tick = rdtsc();
 return m_fTime;
}

double rdtscTimer::Stop(void)
{
 if (m_eState == STOPPED)
  return m_fTime;
 m_eState = STOPPED;
 m_end_tick = rdtsc();
 m_fTime = double(m_end_tick-m_start_tick)/second_per_tick;
 return m_fTime;
}

讓地獄深紅的天亮 發表在 痞客邦 PIXNET 留言(0) 人氣()