How do I get the CPU speed and total physical ram in C#?
I need a simple way of checking how much ram and fast the CPU of the host PC is. I tried WMI however the code I'm using
private long getCPU()
{
ManagementClass mObject = new ManagementClass("Win32_Processor");
mObject.Get();
return (long)mObject.Properties["MaxClockSpeed"].Value;
}
Throws a null reference exception. Furthermore, WMI queries are a bit slow and I need to make a few to get all the specs. Is ther开发者_JAVA百科e a better way?
http://dotnet-snippets.com/dns/get-the-cpu-speed-in-mhz-SID575.aspx
using System.Management;
public uint CPUSpeed()
{
ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
uint sp = (uint)(Mo["CurrentClockSpeed"]);
Mo.Dispose();
return sp;
}
RAM can be found in this SO question: How do you get total amount of RAM the computer has?
You should use PerformanceCounter
class in System.Diagnostics
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
public string getCurrentCpuUsage(){
cpuCounter.NextValue()+"%";
}
public string getAvailableRAM(){
ramCounter.NextValue()+"MB";
}
Much about the processor including its speed in Mhz is available under HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor
I'm running 2 Win7x64 pcs and for some reason the WMI query shows a vague number the first time I run the code and the correct processor speed the second time I run it?
When it comes to performance counters, I did work a LOT with the network counters and got in accurate results and eventually had to find a better solution, so I dont trust them!
精彩评论