高精度定时器的设计
以下是定时器的设计:
#include <windows.h>
#pragma once
inline unsigned __int64 GetCycleCount(void)
{
_asm _emit 0x0F
_asm _emit 0x31
}
//注意事项: 时刻防止数据溢出
class KTimer
{
unsigned __int64 m_startcycle;
unsigned __int64 m_endcycle;
public:
unsigned __int64 m_overhead; //Clock Cycles
unsigned __int64 m_CPUMHz;
KTimer(void)
{
m_overhead = 0;
Start();
Stop();
m_overhead = m_endcycle;
CPUSpeedMHz();
}
//启动CPU时钟
void Start(void)
{
m_startcycle = GetCycleCount();
}
//停止CPU时钟
void Stop()
{
m_endcycle = GetCycleCount() - m_startcycle - m_overhead;
}
//获取时间,false为微秒,TRUE为毫秒,默认为false
__int64 GetTimer(BOOL s_nm = FALSE)
{
if (!s_nm)
{
return m_endcycle / m_CPUMHz;
}
else
{
return m_endcycle / (m_CPUMHz * 1000);
}
}
private:
//获取CPU时钟
void CPUSpeedMHz()
{
__int64 start = GetCycleCount();
Sleep(1000);
m_CPUMHz = (GetCycleCount() - m_overhead - start) / 1000000;
}
};
使用方法如下:
#include <iostream>
#include "Ktimer.h"
using namespace std;
int main()
{
KTimer kt;
kt.Start();
Sleep(150);
kt.Stop();
cout<<kt.GetTimer( )<<" "<<kt.m_overhead<<" "<<kt.m_CPUMHz<<endl;
}