Will Perone

So you want to know how to get the CPU speed of the system. Thankfully since the Pentium class of processors there has been a handly little asm instruction called rdtsc that is going to provide us with exactly the means we need to determine this.
First thing's first, let's write a simple inline function to read the Pentium Time Stamp Register (TSC)
inline __int64 Cycle()
{
	unsigned int L,H;
	__asm
	{
		rdtsc              // RDTSC  -  Pentium+ time stamp register to EDX:EAX.
		mov   [L],eax      // Save low value.
		mov   [H],edx      // Save high value.
	}		
	return ((__int64)L + ((__int64)H<<32));
}
An optimization for this Cycle routine if you are just going to be using it to determine CPU Speed is to just return the low part so that you don't need to work with __int64's
Now the CPU speed function is simply reading the TSC, waiting for a second and reading it again and doing a subtraction. Now since CPU's are so fast now days you usually don't need to wait for an entire second to obtain the CPU speed; you can get a perfectly accurate result by only waiting for instance 1/10 of a second and multiplying the result by 10
__int64 CPUSpeed()
{
	__int64 start, end;

	start= Cycle();
	Sleep(1000 / 10); // this is mostly accurate, for perfect actual Hz do a 1 full second sleep
	end= Cycle();
	return (end-start)*10;
}
The __int64 is a Microsoft Specific keyword denoting a 64bit integer, the equivalent of this is long long. The equivalent call to Sleep(milliseconds) in unix is usleep(microseconds * 1000).
So how do you determine if the processor you are running on has the RDTSC call? Well SDL has an excellent way of checking for this in its CPUInfo stuff. Check out the function CPU_haveRDTSC in the SDL Source. I have an implementation of CPUSpeed in my timer utility
No Comments yet, be the first!
<- for private contact