日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

在NET?Core?中獲取?CPU?使用率_ASP.NET

作者:DotNetCore實戰? ? 更新時間: 2022-03-25 編程語言

以下文章來源于微信公眾號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 使用率內容請搜索AB教程網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持AB教程網!

欄目分類
最近更新