.net core cpu usage for machine

空扰寡人 提交于 2021-01-28 11:32:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!