在C#中以百分比(%)获取内存使用率

时间:2013-04-26 10:04:36

标签: performance memory memory-management cpu-usage performancecounter

我想以百分比(%)获取特定进程的内存使用情况。下面是我用于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();
}

1 个答案:

答案 0 :(得分:1)

性能计数器并不是一个好主意。 请改用此代码:

var wmiObject = new ManagementObjectSearcher("select * from Win32_OperatingSystem");

var memoryValues = wmiObject.Get().Cast < ManagementObject > ().Select(mo = > new {
    FreePhysicalMemory = Double.Parse(mo["FreePhysicalMemory"].ToString()),
    TotalVisibleMemorySize = Double.Parse(mo["TotalVisibleMemorySize"].ToString())
}).FirstOrDefault();

if (memoryValues != null) {
    var percent = ((memoryValues.TotalVisibleMemorySize - memoryValues.FreePhysicalMemory) / memoryValues.TotalVisibleMemorySize) * 100;
}