⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rdtsctimer.cpp

📁 VIGASOCO (VIdeo GAmes SOurce COde) Windows port (v0.01)
💻 CPP
字号:
// RDTSCTimer.cpp
//
/////////////////////////////////////////////////////////////////////////////

#include "RDTSCTimer.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

/////////////////////////////////////////////////////////////////////////////
// initialization and cleanup
/////////////////////////////////////////////////////////////////////////////

RDTSCTimer::RDTSCTimer()
{
}

RDTSCTimer::~RDTSCTimer()
{
}

bool RDTSCTimer::init()
{
	// if the CPU doesn't support the RDTSC instruction, init fails
	if (!supportsRDTSC()){
		return false;
	}

	_ticksPerSecond = calcTicksPerSecond();
	return true;
}

void RDTSCTimer::end()
{
}

/////////////////////////////////////////////////////////////////////////////
// timer methods
/////////////////////////////////////////////////////////////////////////////

INT64 RDTSCTimer::getTime()
{
	INT64 result;

	__asm {
		rdtsc
		lea ebx,[result]
		mov [ebx],eax
		mov [ebx+4],edx
	}

	return result;
}

INT64 RDTSCTimer::getTicksPerSecond()
{
	return _ticksPerSecond;
}

void RDTSCTimer::sleep(UINT32 milliseconds)
{
	Sleep(milliseconds);
}

/////////////////////////////////////////////////////////////////////////////
// helper methods
/////////////////////////////////////////////////////////////////////////////

INT64 RDTSCTimer::calcTicksPerSecond()
{
	// raise the priority for accurate timing
	int priClass = GetPriorityClass(GetCurrentProcess());
	SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
	int priority = GetThreadPriority(GetCurrentThread());
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);

	// wait for 0.25 seconds
	INT64 begin = RDTSCTimer::getTime();

	Sleep(1000/4);

	INT64 end = RDTSCTimer::getTime();

	// restore the previous priority
	SetPriorityClass(GetCurrentProcess(), priClass);
	SetThreadPriority(GetCurrentThread(), priority);

	return (end - begin)*4;
}

bool RDTSCTimer::supportsRDTSC()
{
	int cpuFeatures;

	__asm {
		mov eax, 1
		cpuid
		mov cpuFeatures, edx
	}

	return ((cpuFeatures & 0x10) == 0x10);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -