views:

156

answers:

5

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.

+2  A: 

I assume this is for some form of simulated load testing? Here's one example

AdaTheDev
+1  A: 

well, you can make an infinite loop, with timer -that toggle a sleep function for 8 milliseconds after 2 milliseconds) it is not a real 20% but there is no such thing as real 20%. you will just make it busy for 20% of the time.

notice that a. if you have multi-core cpu... you will need a thread for each core probably to make it grab all core 20% cpu, maybe double it for HT.. you need to check)

Dani
+3  A: 
statenjason
This would be a good way to get your CPU down to 80%, but I think it may have slightly different effects in comparison to a more direct approach. Such as never causing a theoretical program to sleep.
Guvante
I don't think this is available for all computers..
Earlz
@earlz It should be in Vista and Win7. Not sure about XP.
statenjason
@Guvante, it's true that it's not an actual load simulation because it doesn't increase active processes/threads. However, it will meet the criteria he asked of "I want my CPU to run at 80% power."
statenjason
+2  A: 

step 1: Run a cpu intensive loop timing how long it takes to run
step 2: Sleep for 4 times as long as step 1 took.
repeat

You can tune step1 to take microseconds, milliseconds or seconds depending on what type of measurements you are doing

gnibbler
+2  A: 

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.

Neil Fenwick