我想以百分比 (%) 获取特定进程的内存使用情况。下面是我用于 CPU 的代码。但是我无法为内存获得相同的结果。内存性能中的计数器太多了,我很困惑如何计算,或者我们可以直接以百分比 (%) 显示。
static void Main(string[] args)
{
int i = 0;
try
{
PerformanceCounterCategory cpuProcessCategory = new PerformanceCounterCategory("Process");
string[] instanceNames = cpuProcessCategory.GetInstanceNames();
Thread.Sleep(5000);
foreach (string name in instanceNames)
{
try
{
PerformanceCounter cpuProcess = new PerformanceCounter("Process", "% Processor Time", name);
PerformanceCounter memProcess = new PerformanceCounter("Memory", "Available KBytes");
cpuProcess.NextValue();
//Thread.Sleep(5000);
float cpuUsage = cpuProcess.NextValue();
float memUsage = memProcess.NextValue();
//Console.ForegroundColor = ConsoleColor.Yellow;
//Console.Write("Process:'{0}' CPU Usage: {1}% RAM Free: {2}KB", name, cpuUsage, memUsage);
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Process: '{0}' ", name);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("CPU Usage: {0}% ", cpuUsage);
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("RAM Free: {0}KB", memUsage);
Console.WriteLine("");
i++;
}
catch
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("Cannot read CPU Usage for process: {0}", name);
}
}
}
catch
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("Cannot retrieve Performance Counter statistics");
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Total no. of processes: " + i);
Console.ReadLine();
}