views:

912

answers:

2

I've found the following code from here "http://www.boyet.com/Articles/CodeFromInternet.html".
It returns the speed of the CPU in GHz but works only on 32bit Windows.

using System;
using System.Management;

namespace CpuSpeed
{
    class Program
    {
        static double? GetCpuSpeedInGHz()
        {
            double? GHz = null;
            using (ManagementClass mc = new ManagementClass("Win32_Processor"))
            {
                foreach (ManagementObject mo in mc.GetInstances())
                {
                    GHz = 0.001 * (UInt32) mo.Properties["CurrentClockSpeed"].Value;
                    break;
                }
            }
            return GHz;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("The current CPU speed is {0}", (GetCpuSpeedInGHz() ?? -1.0).ToString());
            Console.ReadLine();
        }
    }
}


I've searched for 64bit management classes, but without success.
Is there any other method to get the CPU speed under 64bit Windows?

+5  A: 

Code below should do the trick

  RegistryKey registrykeyHKLM = Registry.LocalMachine;
  string keyPath = @"HARDWARE\DESCRIPTION\System\CentralProcessor\0";
  RegistryKey registrykeyCPU = registrykeyHKLM.OpenSubKey(keyPath, false);
  string MHz = registrykeyCPU.GetValue("~MHz").ToString();
  string ProcessorNameString = (string)registrykeyCPU.GetValue("ProcessorNameString");
  registrykeyCPU.Close();
  registrykeyHKLM.Close();
  Console.WriteLine("{0} MHz for {1}", MHz, ProcessorNameString);
Binoj Antony
I've rewritten the code as contained some bugs and only returned the MHz for CPU/code 0. See my marked reply. Thanks a lot for your code as well.
Marc
A: 

I've used the following code based on the answer by Binoj Antony which returns the speed for each CPU/core, not only the first one:

Microsoft.Win32.RegistryKey registrykeyHKLM = Microsoft.Win32.Registry.LocalMachine;
string cpuPath = @"HARDWARE\DESCRIPTION\System\CentralProcessor";
Microsoft.Win32.RegistryKey registrykeyCPUs = registrykeyHKLM.OpenSubKey(cpuPath, false);
StringBuilder sbCPUDetails = new StringBuilder();
int iCPUCount;
for (iCPUCount = 0; iCPUCount < registrykeyCPUs.SubKeyCount; iCPUCount++)
{
    Microsoft.Win32.RegistryKey registrykeyCPUDetail = registrykeyHKLM.OpenSubKey(cpuPath + "\\" + iCPUCount, false);
    string sMHz = registrykeyCPUDetail.GetValue("~MHz").ToString();
    string sProcessorNameString = registrykeyCPUDetail.GetValue("ProcessorNameString").ToString();
    sbCPUDetails.Append(Environment.NewLine + "\t" + string.Format("CPU{0}: {1} MHz for {2}", new object[] { iCPUCount, sMHz, sProcessorNameString }));
    registrykeyCPUDetail.Close();
}
registrykeyCPUs.Close();
registrykeyHKLM.Close();
sCPUSpeed = iCPUCount++ + " core(s) found:" + sbCPUDetails.ToString();

Fell free to customize it for your needs.

Marc
does this return the current speed or the maximum speed?
Nathan Fellman