.net核心CPU的机器使用情况 [英] .net core cpu usage for machine
本文介绍了.net核心CPU的机器使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我最近从c#迁移到了.net core.在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核心 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屋!
查看全文