在做程序性能分析工具(profiler),需要顺便得到系统硬件的静态信息,以及实时的动态信息。部分代码如下
class HardWare
{
private MEMORY_INFO mi = new MEMORY_INFO();
/// <summary>
/// 获取内存占用率
/// </summary>
/// <returns></returns>
public uint getMemoryUsage()
{
ExternC.GlobalMemoryStatus(ref mi);
return mi.dwMemoryLoad;
}
/// <summary>
/// 获取系统物理内存大小
/// </summary>
/// <returns></returns>
public static string getPhysicalMemorySize()
{
ManagementClass osClass = new ManagementClass("Win32_PhysicalMemory");
ulong Capacity = 0;
StringBuilder CapacityString = new StringBuilder();
foreach (ManagementObject obj in osClass.GetInstances())
{
if (obj["Capacity"] != null)
{
ulong CurrentCapacity = (ulong)obj["Capacity"] / 1024 / 1024 / 1024;
Capacity += CurrentCapacity;
CapacityString.Append(string.Format("+{0}GB", CurrentCapacity));
}
}
return string.Format("{0}GB ({1})", Capacity, CapacityString.ToString().TrimStart('+', ' '));
}
/// <summary>
/// 获取操作系统信息
/// </summary>
/// <returns></returns>
public static string getOsInfo()
{
StringBuilder sb_os = new StringBuilder();
if (Environment.Is64BitOperatingSystem)
sb_os.Append("64Bit ");
else
sb_os.Append("32Bit ");
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
sb_os.Append(key.GetValue("ProductName"));
//sb_os.Append(" ");
//sb_os.Append(key.GetValue("CurrentVersion"));
return sb_os.ToString();
}
/// <summary>
/// 获取处理器信息
/// </summary>
/// <returns></returns>
public static string getProcessorInfo()
{
StringBuilder sb_processor = new StringBuilder();
if (Environment.Is64BitProcess)
sb_processor.Append("64Bit ");
else
sb_processor.Append("32Bit ");
sb_processor.Append(Environment.ProcessorCount + "cores ");
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0");
sb_processor.Append(key.GetValue("ProcessorNameString"));
return sb_processor.ToString();
}
/// <summary>
/// 获取显卡信息
/// </summary>
/// <returns></returns>
public static string getVideoCardInfo()
{
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(@"root\CIMV2", "SELECT * FROM Win32_VideoController");
string string_gpu = "";
foreach (ManagementObject info in searcher1.Get())
{
string_gpu += "+" +info["Caption"].ToString();
}
return string_gpu.Substring(1);
}
}
一下代码获取CPU的占用率,以及各个核的占用率。
PerformanceCounter pc = new PerformanceCounter("Processor", "% Processor Time", "_Total");//通过pc.NextValue可以获取CPU占用率的值
PerformanceCounter[] counters = new PerformanceCounter[System.Environment.ProcessorCount];
for (int i = 0; i < counters.Length; i++)
{
counters[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
}