- 1 year ago
How to measure CPU usage and memory for a process using .NET Core 3.1 for Windows, Linux and macOS?
Comment
1 / 1
To measure CPU usage and memory for a process using .NET Core 3.1 on Windows, Linux, and macOS, you can utilize platform-specific APIs and libraries. Here are the approaches for each platform:
Windows:
- For CPU usage, you can use the
Process.TotalProcessorTime
property to retrieve the total CPU time used by the process. - For memory usage, you can use the
Process.WorkingSet64
property to obtain the working set size of the process (the amount of physical memory used).
Linux:
- For CPU usage, you can read the
/proc/[process_id]/stat
file and extract the necessary CPU-related information. Theutime
andstime
fields provide the user and system CPU time, respectively. - For memory usage, you can read the
/proc/[process_id]/status
file and retrieve theVmRSS
field, which represents the resident set size (RSS) or the amount of physical memory used.
macOS:
- For CPU usage, you can use the
Process.TotalProcessorTime
property similarly to Windows. - For memory usage, you can use the
Process.WorkingSet64
property similarly to Windows.
Here's an example code snippet that demonstrates how to measure CPU usage and memory for a process using .NET Core 3.1:
csharpusing System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main(string[] args)
{
int processId = Process.GetCurrentProcess().Id;
Process process = Process.GetCurrentProcess();
TimeSpan lastTotalProcessorTime = process.TotalProcessorTime;
long lastWorkingSet = process.WorkingSet64;
// Measure CPU usage and memory periodically
while (true)
{
// Calculate CPU usage
TimeSpan currentTotalProcessorTime = process.TotalProcessorTime;
double cpuUsage = (currentTotalProcessorTime - lastTotalProcessorTime).TotalMilliseconds /
(Environment.ProcessorCount * Environment.TickCount);
// Calculate memory usage
long currentWorkingSet = process.WorkingSet64;
long memoryUsage = currentWorkingSet - lastWorkingSet;
Console.WriteLine($"CPU Usage: {cpuUsage:F2}%");
Console.WriteLine($"Memory Usage: {memoryUsage / 1024} KB");
lastTotalProcessorTime = currentTotalProcessorTime;
lastWorkingSet = currentWorkingSet;
// Wait for some time before measuring again
Thread.Sleep(1000);
}
}
}
Keep in mind that the code provided is a simplified example and may need further refinement or adaptation to suit your specific requirements or target platform. Additionally, platform-specific APIs and file system access may have different behaviors or require additional permissions, so make sure to handle any exceptions and implement appropriate error handling in your code.