Tuesday 7 September 2010

Get CPU speed

This is some code that I "borrowed" from the PCSX2 source code and created a small program out of it, the PCSX2 source code is GNU so I don't think this is a problem. This code works nicely but will probably only compile in Visual C++, as the "__rdtsc()" function is microsoft specific.

Sorry about the way the HTML interprets the include directives as code tags and terminates them at the end of the code by the way... can't be helped
#include 
#include 

// Link the library we need for the timeGetTime() function
#pragma comment (lib, "WINMM.LIB")

__int64 getCPUSpeed(unsigned int time)
{
    __int64 timeStart, timeStop;
    __int64 startTick, endTick;
    __int64 overhead;

 overhead = __rdtsc() - __rdtsc();
 
 timeStart = timeGetTime();
 while(timeGetTime() == timeStart) 
    {
  timeStart = timeGetTime();
    }
 for(;;)
 {
  timeStop = timeGetTime();
  if ((timeStop - timeStart) > 1) 
  {
   startTick = __rdtsc();
   break;
  }
 }

 timeStart = timeStop;
 for(;;)
 {
  timeStop = timeGetTime();
  if ((timeStop - timeStart) > time) 
  {
   endTick = __rdtsc();
   break;
  }
 }

 return (__int64)((endTick - startTick) + (overhead));
}

int main()
{
 char *cpuSpeed = (char*)malloc(24);
 sprintf(cpuSpeed, "%d", getCPUSpeed(1000) / 1000000);  // Get CPU speed

 printf("CPU Speed: %c.%c%c%cGhz", cpuSpeed[0], cpuSpeed[1], cpuSpeed[2], cpuSpeed[3]);

 getchar();
 return 0;
}

2 comments: