Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eating up processing power

In C#, is there a way to make a program that simply "eats" roughly 20% of my processing power? In other words, I want my CPU to run at 80% power.

like image 655
Icemanind Avatar asked Mar 28 '26 09:03

Icemanind


1 Answers

Quick background: In reality a CPU is either busy or not, 100% or 0%. Operating systems just do a running average over a short period of time to give you an idea of how often your CPU is crunching.

You didn't specify if you want to do this for a specific core, or as an average across all CPU cores... I'll describe the latter - you'll need to run this code in 1 thread for every core.

Look in the System.Diagnostics namespace and find performance counters.

protected PerformanceCounter cpuCounter;

cpuCounter = new PerformanceCounter();

cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total"; 

I would probably attach to the "Processor" performance counters (Total, not per core). You may want to keep a short running average in your code too.

In your for-loop, check the value of your Processor usage and depending on whether its near your threshold, sleep for a longer or shorter interval... (you might increment/decrement your sleep delay more or less depending on how far away you are from ideal load)

If you get the running average, and your sleep increment/decrement values right, your program should self-tune to get to the right load.

like image 143
Neil Fenwick Avatar answered Mar 29 '26 22:03

Neil Fenwick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!