Search code examples
c#.netwindows64-bitcpu-speed

How to detect CPU speed on Windows 64bit?


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?


Solution

  • 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.