Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net core cpu usage for machine

Tags:

c#

.net

.net-core

I recently migrated from c# to .net core. In c# I use to get CPU usage with this:

PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;

cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");

public string getCurrentCpuUsage(){
            return cpuCounter.NextValue()+"%";
}

but in .net core PerformanceCounter is not available what is the solution ? please give me an advice.

like image 694
Alian Drovez Avatar asked Dec 04 '25 00:12

Alian Drovez


1 Answers

Performance counters are not in Linux thus not in NET Core. Alternative way:

private async Task<double> GetCpuUsageForProcess()
{
    var startTime = DateTime.UtcNow;
    var startCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds);
    await Task.Delay(500);

    var endTime = DateTime.UtcNow;
    var endCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds);
    var cpuUsedMs = endCpuUsage - startCpuUsage;
    var totalMsPassed = (endTime - startTime).TotalMilliseconds;
    var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);
    return cpuUsageTotal * 100;
}
like image 122
Melih Altıntaş Avatar answered Dec 06 '25 15:12

Melih Altıntaş



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!