标签:
//!微秒级别的计时器
//ExactTimer.h
#pragma once
#include <math.h>
BOOL ReadDwordKey(IN HKEY hRootKey,IN LPCTSTR lpSubKey,
IN LPCTSTR lpKey,OUT DWORD& dwValue){
HKEY hk;
if (ERROR_SUCCESS!=RegOpenKey(hRootKey,lpSubKey,&hk))
return FALSE;
DWORD dwType=REG_DWORD,dwLength=sizeof(DWORD);
if (ERROR_SUCCESS!=RegQueryValueEx(hk,lpKey,NULL,&dwType,(LPBYTE)&dwValue,&dwLength))
return FALSE;
RegCloseKey(hk);
if (dwType!=REG_DWORD)
return FALSE;
return TRUE;
}
class CExactTimer
{
public:
/**
* 构造函数:将获取CPU的主频,精确到MHz
*/
CExactTimer(){}
~CExactTimer(void){}
/**
* 获取流逝的时间,us
*/
double GetTimeSpanMicrosecond(){
DWORD dwCpuFrequency=0;
if (!ReadDwordKey(HKEY_LOCAL_MACHINE,_T("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"),_T("~MHz"),dwCpuFrequency))
return -1;
return (_EndTime-_StartTime)/(dwCpuFrequency*1.0);
}
/**
* 停止计时
*/
void Stop(){
_EndTime=GetCycleCount();
}
/**
* 开始计时
*/
void Start(){
_StartTime=GetCycleCount();
}
private:
unsigned __int64 _StartTime;
unsigned __int64 _EndTime;
double _nFrequencyMHz;
inline unsigned __int64 GetCycleCount(){
//RDTSC-Read Time-Stamp Counter
//自开机以来CPU经历的时钟周期数
__asm
{
_emit 0x0F;
_emit 0x31;
}
}
};
使用方法:
CExactTimer TimeSpan;
TimeSpan.Start();
int i=100000;
while(--i);
TimeSpan.Stop();
TRACE("%1.6fus\n",TimeSpan.GetTimeSpanMicrosecond());
RDTSC指令实现微秒级计时器
标签:
原文地址:http://www.cnblogs.com/dgx/p/5491511.html