在NET Core 中获取 CPU 使用率

Adelle ·
更新时间:2024-09-20
· 967 次阅读

以下文章来源于微信公众号DotNetCore实战 

.NET Framework 中,很多人会用 PerformanceCounter 类做这件事情,

如下代码:

    public class Program     {         public static void Main(string[] args)         {             while (true)             {                 var cpuUsage = GetCpuUsageForProcess();                 Console.WriteLine(cpuUsage);             }         }         private static int GetCpuUsageForProcess()         {             var currentProcessName = Process.GetCurrentProcess().ProcessName;             var cpuCounter = new PerformanceCounter("Process", "% Processor Time", currentProcessName);             cpuCounter.NextValue();             return (int)cpuCounter.NextValue();         }     }

PerformanceCounter.NETCore 中是没有的,所以只能采用其他方式了,其实在 System.Diagnostics.Process 类中有一个 TotalProcessorTime 属性,它可以准实时的统计当前进程所消耗的CPU处理器时间,

如下代码:
   

class Program     {         public static async Task Main(string[] args)         {             var task = Task.Run(() => ConsumeCPU(50));             while (true)             {                 await Task.Delay(2000);                 var cpuUsage = await GetCpuUsageForProcess();                 Console.WriteLine(cpuUsage);             }         }         public static void ConsumeCPU(int percentage)         {             Stopwatch watch = new Stopwatch();             watch.Start();             while (true)             {                 if (watch.ElapsedMilliseconds > percentage)                 {                     Thread.Sleep(100 - percentage);                     watch.Reset();                     watch.Start();                 }             }         }         private static async Task<double> GetCpuUsageForProcess()         {             var startTime = DateTime.UtcNow;             var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;             await Task.Delay(500);             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);             return cpuUsageTotal * 100;         }     }

可以看到程序每2s输出一次,观察到 output 和 任务管理器 中的CPU利用率基本是一致的。

到此这篇关于在NET Core 中获取 CPU 使用率的文章就介绍到这了,更多相关NET Core 中获取 CPU 使用率内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!

译文链接:https://medium.com/@jackwild/getting-cpu-usage-in-net-core-7ef825831b8b



使用率 net core

需要 登录 后方可回复, 如果你还没有账号请 注册新账号