Click here to Skip to main content
15,861,168 members
Articles / Desktop Programming / MFC
Article

Get the Processor Speed in two simple ways

Rate me:
Please Sign up or sign in to vote.
4.79/5 (35 votes)
12 Jun 2004CPOL1 min read 167.8K   2.2K   27   19
Get the frequency of the processor either from the registry, or calculate it.

Sample Image - Processor_Speed.gif

Introduction

I'll show you two ways to retrieve the processor-speed (frequency in MHz). With two simple functions, one to retrieve the frequency from the registry of your Windows operating system, and one to calculate it with the clock cycles and a high resolution counter. If you want to use the function to calculate the speed (frequency), you have to use it with a Pentium instruction set compatible processor (look at the lines below).

rfmobile wrote in a message:

You don't need to change the RDTSC definition for non-Intel processors. The code works as-is on my AMD mobile Athlon. Should work on any Pentium instruction set compatible processor but not for 486 or 386.

I'm not able to verify this, so I would like to hear some feedback.

BTW: Constructive criticism is always welcome! :-)

Routine to retrieve the speed (frequency) from the registry:

This is plain code to retrieve a registry value as a CString:

CString ProcSpeedRead()
{
CString sMHz;
char Buffer[_MAX_PATH];
DWORD BufSize = _MAX_PATH;
DWORD dwMHz = _MAX_PATH;
HKEY hKey;

// open the key where the proc speed is hidden:
long lError = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                        "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
                        0,
                        KEY_READ,
                        &hKey);
    
    if(lError != ERROR_SUCCESS)
      {// if the key is not found, tell the user why:
           FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                         NULL,
                         lError,
                         0,
                         Buffer,
                         _MAX_PATH,
                         0);
               AfxMessageBox(Buffer);
           return "N/A";
       }

        // query the key:
        RegQueryValueEx(hKey, "~MHz", NULL, NULL, (LPBYTE) &dwMHz, &BufSize);

    // convert the DWORD to a CString:
    sMHz.Format("%i", dwMHz);

return sMHz;
}

Routine to calculate the processor frequency in MHz:

Retrieve the frequency in MHz as a floating-point number. I use some well documented (at least for me ;-)) assembler here:

float CGettheProcessorSpeedDlg::ProcSpeedCalc()
{
/*
RdTSC:
It's the Pentium instruction "ReaD Time Stamp Counter". It measures the
number of clock cycles that have passed since the processor was reset, as a
64-bit number. That's what the <CODE>_emit</CODE> lines do.*/
#define RdTSC __asm _emit 0x0f __asm _emit 0x31

// variables for the clock-cycles:
__int64 cyclesStart = 0, cyclesStop = 0;
// variables for the High-Res Preformance Counter:
unsigned __int64 nCtr = 0, nFreq = 0, nCtrStop = 0;


    // retrieve performance-counter frequency per second:
    if(!QueryPerformanceFrequency((LARGE_INTEGER *) &nFreq)) return 0;

    // retrieve the current value of the performance counter:
    QueryPerformanceCounter((LARGE_INTEGER *) &nCtrStop);

    // add the frequency to the counter-value:
    nCtrStop += nFreq;


    _asm
        {// retrieve the clock-cycles for the start value:
            RdTSC
            mov DWORD PTR cyclesStart, eax
            mov DWORD PTR [cyclesStart + 4], edx
        }

        do{
        // retrieve the value of the performance counter
        // until 1 sec has gone by:
             QueryPerformanceCounter((LARGE_INTEGER *) &nCtr);
          }while (nCtr < nCtrStop);

    _asm
        {// retrieve again the clock-cycles after 1 sec. has gone by:
            RdTSC
            mov DWORD PTR cyclesStop, eax
            mov DWORD PTR [cyclesStop + 4], edx
        }

// stop-start is speed in Hz divided by 1,000,000 is speed in MHz
return    ((float)cyclesStop-(float)cyclesStart) / 1000000;
}

Credits

  • I got the assembler some time ago from an assembler newsgroup
  • ...and credits to all programmers out there who share their knowing!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Germany Germany
My name is Thomas, I'm born on January the 11th in
1970, right now I'm working in the Quality department
of a big Pipe mill as a Technician.
My hobbies are my girl friend, my car, RC-Planes and
Computers. I begun with VC++ some time ago and now
Programming is like a drug to me (I'm still a
beginner). I want to learn it all in a blink of an
eye Wink | ;-) but i know that this is not possible. It's
real fun for me and I do small Programms for my own
use.
O.K. enough written..... I need my Time to debug
everything that crosses my way! Wink | ;-)

Comments and Discussions

 
SuggestionCalculations or output are ambiguous? Pin
Member 100992673-Mar-15 2:39
Member 100992673-Mar-15 2:39 
Generalwin api Pin
swidro17-Feb-11 7:38
swidro17-Feb-11 7:38 
GeneralWorks on AMD Athlon 64 4200+ Pin
Gandi13378-Mar-10 15:12
Gandi13378-Mar-10 15:12 
GeneralThis + an algorithm could be new way to get random numbers Pin
JestBlaze13-Apr-08 15:22
JestBlaze13-Apr-08 15:22 
QuestionWhy waiting that second? Pin
Anonymous28-Jul-04 23:58
Anonymous28-Jul-04 23:58 
GeneralAccuracy not guaranteed Pin
David Crow17-Jun-04 8:05
David Crow17-Jun-04 8:05 
GeneralThe code I'm posting here has always worked for me Pin
Olan Patrick Barnes14-Jun-04 9:14
Olan Patrick Barnes14-Jun-04 9:14 
GeneralRe: The code I'm posting here has always worked for me Pin
Thomas Latuske14-Jun-04 10:39
Thomas Latuske14-Jun-04 10:39 
GeneralGet Processor Speed should be Get Processor Frequency Pin
technomanceraus8-Jun-04 19:30
technomanceraus8-Jun-04 19:30 
GeneralRe: Get Processor Speed should be Get Processor Frequency Pin
RichardGrimmer9-Jun-04 4:18
RichardGrimmer9-Jun-04 4:18 
GeneralRe: Get Processor Speed should be Get Processor Frequency Pin
Anonymous13-Jun-04 17:21
Anonymous13-Jun-04 17:21 
GeneralRe: Get Processor Speed should be Get Processor Frequency Pin
Vince C.14-Jun-04 22:22
Vince C.14-Jun-04 22:22 
I would say indeed speed is the measure of the amount of work something - like a CPU, for instance - can achieve in one second. The start looks correct to me. Then the amount of work of a CPU fits IMHO the number of *instructions* per second rather than the number of beats per second.

Frequency just gives the average clock speed. A CPU speed is expressed in instructions per second. So unless your CPU is a RISC (which is certainly not the case of an INTEL CPU, or are you talking about how hyperthreading is achieved...), in which case an instruction equals a clock pulse, one instruction is not equal to one hertz.

To make a log story short, the figure you are retrieving is an instant computation of the average CPU clock speed. It is not the CPU inherent speed but only it's clock speed. So it's indeed a frequency.

Now have some aspirins Wink | ;-)


---

Vince C.

GeneralRDTSC Pin
unitrunker8-Jun-04 15:07
unitrunker8-Jun-04 15:07 
GeneralRe: RDTSC Pin
Thomas Latuske13-Jun-04 6:04
Thomas Latuske13-Jun-04 6:04 
GeneralRegistry method works only on NT Pin
dacris8-Jun-04 9:39
dacris8-Jun-04 9:39 
GeneralRe: Registry method works only on NT Pin
Rick York8-Jun-04 10:04
mveRick York8-Jun-04 10:04 
GeneralRe: Registry method works only on NT Pin
Thomas Latuske8-Jun-04 10:43
Thomas Latuske8-Jun-04 10:43 
GeneralCode will break soon... Pin
DiWa8-Jun-04 8:08
DiWa8-Jun-04 8:08 
GeneralRe: Code will break soon... Pin
Thomas Latuske8-Jun-04 9:04
Thomas Latuske8-Jun-04 9:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.