欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年01月25日 17:28:09   作者:DotNetCore實(shí)戰(zhàn)?  
這篇文章我們分享一種如何在?.NETCore?中獲取?CPU使用率的方法,?它所報(bào)告的這個(gè)值和?任務(wù)管理器?中報(bào)告的?CPU?使用值?差不多是一致的,下面來看看文中的具體詳細(xì)介紹吧

以下文章來源于微信公眾號DotNetCore實(shí)戰(zhàn) 

.NET Framework 中,很多人會(huì)用 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 中是沒有的,所以只能采用其他方式了,其實(shí)在 System.Diagnostics.Process 類中有一個(gè) TotalProcessorTime 屬性,它可以準(zhǔn)實(shí)時(shí)的統(tǒng)計(jì)當(dāng)前進(jìn)程所消耗的CPU處理器時(shí)間,

如下代碼:
   

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 和 任務(wù)管理器 中的CPU利用率基本是一致的。

到此這篇關(guān)于在NET Core 中獲取 CPU 使用率的文章就介紹到這了,更多相關(guān)NET Core 中獲取 CPU 使用率內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

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

相關(guān)文章

最新評論