SELA
SELA

Reputation: 6858

How to get RAM and CPU usage percentages that match with values shown in Task Manager

I need to get the percentage of CPU and RAM usage at a given time using .net core 8 WEB API accurately with the figures shown in Task Manager.

The problem I'm facing is the percentages of the value I get for the CPU & RAM usage percentages are not accurate enough when I compare them with Task Manager percentage values.

RAM usage percentage values are close to accurate with values that are being shown in Task Manager.

Code I've tried:

public async Task<void> getCpuUsageData()
{
    try
    {
        var CpuThreadSleepTime = _appSettings.ThreadSleepTimeForCPU; // CpuThreadSleepTime - 30000
        var RamThreadSleepTime = _appSettings.ThreadSleepTimeForRAM; // RamThreadSleepTime - 30000
        var totalMemory = GetTotalPhysicalMemory();
        var totalCpu = GetTotalCpu();
        var ramCounter = new PerformanceCounter("Memory", "Available MBytes");
        var availableMemory = ramCounter.NextValue();
        var usedMemory = totalMemory - availableMemory;
        var usedMemoryPercentage = (usedMemory / totalMemory) * 100;
        var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        cpuCounter.NextValue();
        Thread.Sleep(CpuThreadSleepTime);
        var cpuUsagePercentage = cpuCounter.NextValue();
        var usedCpu = totalCpu - cpuUsagePercentage;
        var usedCpuPercentage = (usedCpu / totalCpu) * 100;

        Console.WriteLine("Used Ram Percentage : " + usedMemoryPercentage);
        Console.WriteLine("Used CPU Percentage : " + usedCpuPercentage);

    }
    catch (Exception ex)
    {
        throw ex;
    }
}


public float GetTotalPhysicalMemory()
{
    try
    {
        float totalMemory = 0;
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem");
        foreach (ManagementObject mo in searcher.Get())
        {
            totalMemory = Convert.ToSingle(mo["TotalPhysicalMemory"]) / (1024 * 1024); // Convert bytes to MB
        }
        return totalMemory;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

public float GetTotalCpu()
{
    try
    {
        int totalCpu = 0;
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT NumberOfLogicalProcessors FROM Win32_Processor");
        foreach (ManagementObject mo in searcher.Get())
        {
            totalCpu += Convert.ToInt32(mo["NumberOfLogicalProcessors"]);
        }
        return (float)totalCpu;
    }
    catch (Exception ex)
    {
        throw ex;
    }

}

I need help in fetching value percentages accurate to the Task Manager-shown figures.

Upvotes: 3

Views: 262

Answers (0)

Related Questions