问题
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.
回答1:
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;
}
来源:https://stackoverflow.com/questions/59465212/net-core-cpu-usage-for-machine