//////////////////////////////////////////////////////////////////////// ///////
// KTimer.h
//
// Windows Graphics Programming Win32 GDI and DirectDraw®
// Feng Yuan
// Publisher: Prentice Hall PTR
// First Edition December 01, 2000
//
// 高精度納秒計時器, 最後修改:
// 2008-12 by [email protected]
/////////////////////////////////////////////////////////////////////////////// /* Usage:
int main()
{
KTimer kt;
unsigned int cpu_speed = kt.CPUSpeedMHz();
kt.Start();
Sleep(1234);
unsigned int elapsed_cyc = (unsigned int) kt.Stop();
printf("CPU Speed: %.2f Ghz. Elapsed %ld CPU Cycles ( %ld Nanosecond)\n",
cpu_speed/1000.f,
elapsed_cyc,
KTimer::CyclesToNanos(elapsed_cyc, cpu_speed));
}
*/
#pragma once
#ifndef STRICT
# define STRICT
#endif
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
inline unsigned __int64 GetCycleCount(void)
{
_asm _emit 0x0F
_asm _emit 0x31
}
class KTimer
{
unsigned __int64 m_startcycle;
public:
unsigned __int64 m_overhead; // Clock Cycles
KTimer(void)
{
m_overhead = 0;
Start();
m_overhead = Stop();
}
// 啟動CPU時鐘
void Start(void)
{
m_startcycle = GetCycleCount();
}
// 停止CPU時鐘, 返回自上一次啟動的時鐘周期數
unsigned __int64 Stop(void)
{
return GetCycleCount()-m_startcycle-m_overhead;
}
// 把以CPU周期數轉為納秒
unsigned __int64 static CyclesToNanos(unsigned __int64 time_cycles, unsigned int speed_mhz)
{
return time_cycles*1000 / speed_mhz;
}
// 把以CPU周期數轉為毫秒
unsigned __int64 static CyclesToMillis(unsigned __int64 time_cycles, unsigned int speed_mhz)
{
return time_cycles / speed_mhz / 1000;
}
// 1GHz = 1000MHz
unsigned int CPUSpeedMHz()
{
Start();
Sleep(1000);
unsigned __int64 cputime = Stop();
return (unsigned int)(cputime/1000000);
}
};