[英]How to measure CPU usage and memory for a process using .NET Core 3.1 for Windows, Linux and macOS?
[英]How to get CPU Usage and Virtual Memory for a process in .Net Core?
在 .NET Core 中,如何獲取給定進程的 CPU 使用率和虛擬 Memory?
谷歌搜索結果顯示 PerformanceCounter 和 DriverInfo class 可以完成這項工作。 但是,PerformanceCounter 和 DriverInfo class 在 .NET 內核中不可用。
stackoverflow 中有一篇關於這個問題的帖子: How to get the current CPU/RAM/Disk usage in a C# web application using .NET CORE?
但是它只解決: -當前進程的 CPU 使用情況:
var proc = Process.GetCurrentProcess();
我已經獲得了進程(使用 ProcessID integer 格式)。 如何獲取 .NET 核心中該特定進程的 CPU 使用率和虛擬 Memory?
您可以在System.Diagnostics.PerformanceCounter
包中使用PerformnceCounter
例如,下一個代碼將為您提供總處理器使用百分比
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
var value = cpuCounter.NextValue();
// In most cases you need to call .NextValue() twice
if (Math.Abs(value) <= 0.00)
value = cpuCounter.NextValue();
Console.WriteLine(value);
您可以使用類似這樣的方法來獲取netcore 進程 memory :
var process = Process.GetCurrentProcess();
var workingSet64 = process.WorkingSet64;
var privateMemorySize64 = process.PrivateMemorySize64;
var virtualMemorySize64 = process.VirtualMemorySize64;
對於CPU 使用率:
private static DateTime? _previousCpuStartTime = null;
private static TimeSpan? _previousTotalProcessorTime = null;
private static double GetCpuUsageForProcess()
{
var currentCpuStartTime = DateTime.UtcNow;
var currentCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
// If no start time set then set to now
if (!_previousCpuStartTime.HasValue)
{
_previousCpuStartTime = currentCpuStartTime;
_previousTotalProcessorTime = currentCpuUsage;
}
var cpuUsedMs = (currentCpuUsage - _previousTotalProcessorTime.Value).TotalMilliseconds;
var totalMsPassed = (currentCpuStartTime - _previousCpuStartTime.Value).TotalMilliseconds;
var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);
// Set previous times.
_previousCpuStartTime = currentCpuStartTime;
_previousTotalProcessorTime = currentCpuUsage;
return cpuUsageTotal * 100.0;
}
我剛剛在 google 中輸入了“獲取 c# 中的所有進程”,然后發現了這個:
Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
}
我在 asp.net core 2.2 中快速測試,它使用 System.Diagnostics 工作正常; 但是我使用 Windows 10 pro 來測試它。 所以我不知道它是否適用於其他操作系統。
資料來源: https : //www.howtogeek.com/howto/programming/get-a-list-of-running-processes-in-c/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.