I’m 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 to assign the process to.
I’d also like to be able to see the usage % of each core. Nothing fancy, a TextBox or Label is fine.
I’ve been trying to use PerformanceCounter after coming across these answers:
CPU usage for more than 2 cores
I tried implementing these as follows:
StatusBarOutput.Text = "";
//ignoring posible hyper-threading for simplicity's 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’m getting is:

Meanwhile, the Task manager is showing this:

Not sure what I’m missing here.
The OS is likely much better at determining which core to use. The folks at MS have spent a lot of time optimizing this particular aspect.
If you try to take it over, are you going to maintain this for every new service pack, version of OS, hardware flavor, etc?
Your best bet is likely to spend some time optimizing the processes, not trying to outguess the OS.
UPDATE:
With performance counters, it’s not quite as simple as just grabbing the first value you find. You need to poll at least twice (with some time in between) to get a value.
This isn’t necessarily how I would implement this in a real world scenario, but here is the idea: