Home > Backend Development > C++ > How to Get CPU Utilization in C# Using PerformanceCounter?

How to Get CPU Utilization in C# Using PerformanceCounter?

DDD
Release: 2025-01-27 07:41:10
Original
880 people have browsed it

How to Get CPU Utilization in C# Using PerformanceCounter?

Monitoring System Resources (CPU and RAM) with C#

This article demonstrates how to efficiently monitor CPU and RAM usage within C# applications. This is crucial for performance analysis and optimization. The PerformanceCounter class from the System.Diagnostics namespace provides the necessary functionality.

To access CPU utilization, you'll need to instantiate a PerformanceCounter object. This involves specifying the category ("Processor"), the counter name ("% Processor Time"), and the instance name ("_Total") for overall CPU usage. Here's how:

PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
Copy after login

Retrieving the CPU usage percentage is done using the NextValue() method. However, the first call returns 0%. For accurate results, call it twice with a short delay (e.g., one second) between calls:

public string GetCurrentCpuUsage()
{
    cpuCounter.NextValue(); //Initial call, discard result
    System.Threading.Thread.Sleep(1000); //Wait one second
    return cpuCounter.NextValue() + "%";
}
Copy after login

This example also shows how to monitor available RAM using another PerformanceCounter targeting "Memory" and "Available MBytes". This provides a comprehensive view of system resource consumption.

In conclusion, the PerformanceCounter class offers a straightforward and effective way to monitor CPU and RAM usage in C#, enabling developers to fine-tune their applications for optimal performance.

The above is the detailed content of How to Get CPU Utilization in C# Using PerformanceCounter?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template