计算机的 .NET 核心 CPU 使用情况



我最近从c#迁移到.net core。在 c# 中,我用来获取 CPU 使用率:

PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
public string getCurrentCpuUsage(){
return cpuCounter.NextValue()+"%";
}

但是在.NET Core中PerformanceCounter不可用的解决方案是什么?请给我一个建议。

性能计数器不在 Linux 中,因此不在 NET Core 中。替代方式:

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;
}

在 Mac 上,我走的路线与你已经必须去获取内存使用情况的路线相同:壳出到命令行实用程序,例如top,并解析输出。

这是我的代码:


private static string[] GetOsXTopOutput()
{
var info = new ProcessStartInfo("top");
info.Arguments = "-l 1 -n 0";
info.RedirectStandardOutput = true;
string output;
using (var process = Process.Start(info))
{
output = process.StandardOutput.ReadToEnd();
}
return output.Split('n');
}
public static double GetOverallCpuUsagePercentage()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var lines = GetOsXTopOutput();
// Example: "CPU usage: 8.69% user, 21.73% sys, 69.56% idle"
var pattern = @"CPU usage: d+.d+% user, d+.d+% sys, (d+.d+)% idle";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
foreach (var line in lines)
{
Match m = r.Match(line);
if (m.Success)
{
var idle = double.Parse(m.Groups[1].Value);
var used = 100 - idle;
return used;
}
}
// Or throw an exception
return -1.0;
}
else
{
// E.g., Melih Altıntaş's solution: https://stackoverflow.com/a/59465268/132042
...
}
}

最新更新