Finding the least used processor core using C #

I am writing a small winforms application that opens several instances of another program. To optimize performance, I'm looking for a way to find the least used CPU core for process assignment.

I would also like to see the% usage of each core. Nothing out of the ordinary, TextBox or Label is fine.

I am trying to use PerformanceCounter after going through these answers:

Kernel Number Search

CPU usage for more than 2 cores

I tried to implement them as follows:

  StatusBarOutput.Text = ""; //ignoring posible hyper-threading for simplicity sake var coreUsages = new PerformanceCounter[Environment.ProcessorCount]; for (var i = 0; i < coreUsages.Length; i++) { coreUsages[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString()); //using the status bar as output for now, doesn't really matter StatusBarOutput.Text += " | " + coreUsages[i].CounterName + " ~ " + coreUsages[i].NextValue(); } 

The output I get is:

output

Meanwhile, the task manager shows this:

output

Not sure what I'm missing here.

+4
source share
3 answers

The OS is probably much better at determining which kernel to use. People at MS have spent a lot of time optimizing this particular aspect.

If you try to make this decision, will you support this for every new service pack, OS version, hardware taste, etc.?

It is best to spend some time optimizing processes without trying to get ahead of the OS.

UPDATE:

With performance counters, it’s not as easy as grabbing the first value you find. You need to poll at least two times (with a certain period of time) to get the value.

It’s not necessary how I will implement it in a real-world scenario, but here is the idea:

 var coreUsages = new PerformanceCounter[Environment.ProcessorCount]; for (var i = 0; i < coreUsages.Length; i++) { coreUsages[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString()); coreUsages[i].NextValue(); } Thread.Sleep(1000); for (var i = 0; i < coreUsages.Length; i++) { //using the status bar as output for now, doesn't really matter Trace.WriteLine(" | " + coreUsages[i].CounterName + " ~ " + coreUsages[i].NextValue()); } 
+6
source

Oh! I can see what it is.

In this line of code:

  coreUsages[i].NextValue(); 

NextValue () returns a float.

If you impose 0.35 (or 35%) on an integer, you get 0.

0
source

For experimentation, I suppose you could use GetCurrentProcess() from the Process class under System.Diagnostics . From the returned process, you can set the ProcessAffinity property depending on which kernel you find has the lowest usage based on your code to calculate usage per kernel.

As others have noted, it is a bad idea to try and do it in a real application.

0
source

Source: https://habr.com/ru/post/1413003/


All Articles