机器的 .net 核心 CPU 使用率 [英] .net core cpu usage for machine
本文介绍了机器的 .net 核心 CPU 使用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我最近从 c# 迁移到 .net 核心.在 c# 中,我用这个来获取 CPU 使用率:
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()+"%";
}
但是在 .net core PerformanceCounter
中不可用有什么解决方案?请给我一个建议.
but in .net core PerformanceCounter
is not available what is the solution ? please give me an advice.
推荐答案
性能计数器不在 Linux 中,因此不在 NET Core 中.替代方式:
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;
}
这篇关于机器的 .net 核心 CPU 使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文