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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With