How to Get the Cpu Usage in C#

How to get total CPU usage (all processes)? (C#)

When you use the PerformanceCounter class the first call of the NextValue() method most likely will return 0. So, you should call it a few times after some delay to get an appropriate measure.

you will need:

using System.Diagnostics;
using System.Threading;

Then you can obtain it as follows:

static void Main(string[] args)
{
var cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");
Thread.Sleep(1000);
var firstCall = cpuUsage.NextValue();

for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
Console.WriteLine(cpuUsage.NextValue() + "%");
}

Console.Read();
}

get current CPU utilization in C#

That's because you need to call NextValue multiple times on the same PerformanceCounter instance (so at least twice). The first call will always return 0.

You can work around this (sort of) by calling NextValue twice in your Page_Load event handler, only storing the return value of the second call:

        float cpuUsage = 0.00F;

this.theCPUCounter.NextValue();
cpuUsage = this.theCPUCounter.NextValue();

The reason it shows in the QuickWatch of the debugger is probably just because it is (implicitly) called multiple times (once by the program and once by the debugger for the QuickWatch value).

Update to the "sort of" above:

As others have mentioned you usually need to sleep some time between the two calls to actually observe a difference in CPU load that results in a "measurable" difference. Sleeping for 1 s usually does the trick, but might not be an acceptable delay in the loading of your page.

What you really want to do is provide a background thread that repeatedly queries this performance counter, sleeping a couple of seconds in between. And storing the result somewhere. From your Page_Load or other events / functions query the (last) value. All with necessary locking against data races of course.
It will be as accurate as you can get with regards to this pointer.

Since you are obviously using ASP.NET you have to be careful with such background threads. I'm no ASP.NET expert, but according to this it should be possible, even though the thread (and the perf counter readings it did) will be recycled, when your app domain / web application is. However, for this kind of functionality that shouldn't be an issue.

Get CPU and RAM usage

There is nothing wrong with your values.

The reason you see differences with what task manager returns is that the "CPU usage" value is something computed for a given interval, i.e. between two NextValue() calls. If task manager "doesn't call its own NextValue" (if we simplify how it works) at the same time you do, you won't return the same results.

Imagine the following scenario:

Time 0: 0% actual CPU usage
Time 1: 50% actual CPU usage
Time 2: 70% actual CPU usage
Time 3: 2% actual CPU usage
Time 4: 100% actual CPU usage
  • If you check the value between Time 1 and Time 3, you'll return something based on "50% and 2%".
  • If task manager checks the value between Time 2 and Time 4, it'll return something different, i.e. a value based on "70% and 100%".

You could try to spawn multiple processes of your own application, you should also see different results.

Get CPU load using GetSystemTimes

As pointed above using performance counters is a much better solution

The keys needed are Processor Information, % Processor Utility & _Total

var PerformanceCounterCPULoad = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total");

// call this every second or so
var percent = (int)PerformanceCounterCPULoad.NextValue();

How to get the CPU Usage in asp.net

As mentioned in comments, without the appropriate permissions you will not be able to do this. Resource statistics will include a lot of information about processes owned by other users of the system which is privileged information

c# calculate CPU usage for a specific application

Performance Counters - Process - % Processor Time.

Little sample code to give you the idea:

using System;
using System.Diagnostics;
using System.Threading;

namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
PerformanceCounter myAppCpu =
new PerformanceCounter(
"Process", "% Processor Time", "OUTLOOK", true);

Console.WriteLine("Press the any key to stop...\n");
while (!Console.KeyAvailable)
{
double pct = myAppCpu.NextValue();
Console.WriteLine("OUTLOOK'S CPU % = " + pct);
Thread.Sleep(250);
}
}
}
}

Notes for finding the instance based on Process ID:

I do not know of any better way, and hopefully somebody does. If not, here is one way you can find the right instance name for your process given the Process ID and process name.

There is another Performance Counter (PC) called "ID Process" under the "Process" family. It returns the PID for the instance. So, if you already know the name (i.e. "chrome" or "myapp"), you can then test each instance until you find the match for the PID.

The naming is simple for each instance: "myapp" "myapp#1" "myapp#2" ... etc.

...  new PerformanceCounter("Process", "ID Process", appName, true);

Once the PC's value equals the PID, you found the right appName. You can then use that appName for the other counters.



Related Topics



Leave a reply



Submit