使用此代码,此方法适用于Windows。对于Linux(Ubuntu)“ Linux中未提供PerformanceCounter”
PerformanceCounter counter = GetPerfCounterForProcessId(process.Id); //Just gets process by id dont worry...
var processUsages = counter.NextValue();
double processUsage = counter.NextValue() / Environment.ProcessorCount;
如何通过ID在Linux上正常运行时转移此方法以从进程中获取CPU使用率?
PerformanceCounter
表示Windows NT性能计数器组件,这意味着它仅可在Windows上运行并在Windows Performance Monitor上侦听。
对于Linux
,您应该使用System.Diagnostics.Process.GetCurrentProcess()
来计算CPU使用率。例:
var startTime = DateTime.UtcNow;
var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
var stopWatch = new Stopwatch();
// Start watching CPU
stopWatch.Start();
// Meansure something else, such as .Net Core Middleware
await _next.Invoke(httpContext);
// Stop watching to meansure
stopWatch.Stop();
var endTime = DateTime.UtcNow;
var endCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
var totalMsPassed = (endTime - startTime).TotalMilliseconds;
var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);
var cpuUsagePercentage = cpuUsageTotal * 100;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句