在NET Core 中獲取 CPU 使用率
阿新 • • 發佈:2022-01-09
以下文章來源於微信公眾號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 = Taskbpavv.Run(() => ConsumeCPU(50)); while (true) { await Task.Delay(2000); var cpuUsage = await GetCpuUsageForProcess(); Console.WriteLine(cpuUsage); } } public static void ConsumeCPU(http://www.cppcns.comint percentage) { Stopwatch watch = new Stopwatch(); watch.Start(); while (true) { http://www.cppcns.comif (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).TotalMillisbpavveconds; 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