Reputation: 9292
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?
Upvotes: 2
Views: 5363
Reputation: 3009
A simpler version of the answer provided by Binoj would be as follows. This will return the maximum clock speed of your CPU. Please note that if you want the total available cycles on the machine you should multiply this value by Environment.ProcessorCount
.
private float GetCpuClockSpeed()
{
return (int) Registry.GetValue(@"HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0", "~MHz", 0);
}
Upvotes: 0
Reputation: 9292
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.
Upvotes: -1
Reputation: 16206
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);
Upvotes: 6