Click here to Skip to main content
11,641,209 members (63,129 online)
Click here to Skip to main content

Get the Processor Speed in two simple ways

, 12 Jun 2004 CPOL 127.9K 1.8K 27
Rate this:
Please Sign up or sign in to vote.
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! Smile | :)

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 Wink | ;-) ) 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)

Share

About the Author

Thomas Latuske
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 | ;-)

You may also be interested in...

Comments and Discussions

 
SuggestionCalculations or output are ambiguous? Pin
Member 100992673-Mar-15 2:39
memberMember 100992673-Mar-15 2:39 
Generalwin api Pin
swidro17-Feb-11 7:38
memberswidro17-Feb-11 7:38 
GeneralWorks on AMD Athlon 64 4200+ Pin
Gandi13378-Mar-10 15:12
memberGandi13378-Mar-10 15:12 
GeneralThis + an algorithm could be new way to get random numbers Pin
JestBlaze13-Apr-08 15:22
memberJestBlaze13-Apr-08 15:22 
QuestionWhy waiting that second? Pin
Anonymous28-Jul-04 23:58
sussAnonymous28-Jul-04 23:58 
GeneralAccuracy not guaranteed Pin
DavidCrow17-Jun-04 8:05
memberDavidCrow17-Jun-04 8:05 
GeneralThe code I'm posting here has always worked for me Pin
Olan Patrick Barnes14-Jun-04 9:14
memberOlan 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
memberThomas Latuske14-Jun-04 10:39 
GeneralGet Processor Speed should be Get Processor Frequency Pin
technomanceraus8-Jun-04 19:30
membertechnomanceraus8-Jun-04 19:30 
GeneralRe: Get Processor Speed should be Get Processor Frequency Pin
RichardGrimmer9-Jun-04 4:18
memberRichardGrimmer9-Jun-04 4:18 
GeneralRe: Get Processor Speed should be Get Processor Frequency Pin
Anonymous13-Jun-04 17:21
sussAnonymous13-Jun-04 17:21 
GeneralRe: Get Processor Speed should be Get Processor Frequency Pin
Vince C.14-Jun-04 22:22
memberVince C.14-Jun-04 22:22 
GeneralRDTSC Pin
rfmobile8-Jun-04 15:07
memberrfmobile8-Jun-04 15:07 
If you want to use the function to calculate 
the speed you have to use it with a Pentium 
Processor. For AMD or any other Processor there 
must be made some modifications (to the RdTSC 
definition I think).

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.


Also, you don't need to #define the RdTSC instruction. The RDTSC and CPUID instructions are already defined in Visual C++ 6 SP5 (or VC++ 7.1). Try this ...


__asm rdtsc;

Also beware that even Intel processors have bugs like this one ...


Y3. RDTSC Instruction May Report the Wrong Time Stamp Counter Value
Problem: The Time Stamp Counter is a 64-bit 
counter that is read in two 32-bit chunks. The 
counter incorrectly advances and therefore the two 
chunks may go out of synchronization causing the 
Read Time Stamp Counter (RDTSC) instruction to 
report the wrong time stamp counter value
Implication: This erratum may cause software to 
see the wrong representation of processor time 
and may result in unpredictable software operation.
Workaround: It is possible for BIOS to contain a 
workaround for this erratum.
Status: For the steppings affected, see the 
Summary of Changes.

Intel® Pentium® M Processor Specification Update

-rick
GeneralRe: RDTSC Pin
Thomas Latuske13-Jun-04 6:04
memberThomas Latuske13-Jun-04 6:04 
GeneralRegistry method works only on NT Pin
dacris8-Jun-04 9:39
memberdacris8-Jun-04 9:39 
GeneralRe: Registry method works only on NT Pin
Rick York8-Jun-04 10:04
memberRick York8-Jun-04 10:04 
GeneralRe: Registry method works only on NT Pin
Thomas Latuske8-Jun-04 10:43
memberThomas Latuske8-Jun-04 10:43 
GeneralCode will break soon... Pin
DiWa8-Jun-04 8:08
memberDiWa8-Jun-04 8:08 
GeneralRe: Code will break soon... Pin
Thomas Latuske8-Jun-04 9:04
memberThomas Latuske8-Jun-04 9:04 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150731.1 | Last Updated 13 Jun 2004
Article Copyright 2004 by Thomas Latuske
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid