Icemanind
Icemanind

Reputation: 48736

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.

Upvotes: 2

Views: 284

Answers (5)

Dani
Dani

Reputation: 15081

Well, you can make an infinite loop with a timer that toggles 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.

Note that if you have multi-core cpu you will need a thread for each core probably to make it busy all cores to 20% cpu; maybe double it for HyperThreading... (you need to check)

Upvotes: 1

Neil Fenwick
Neil Fenwick

Reputation: 6184

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.

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304473

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

Upvotes: 2

statenjason
statenjason

Reputation: 5190

Not exactly using C#, but if you want to set your cpu to only use 80% it can be set in windows power options.

alt text http://img43.imageshack.us/img43/7487/poweroptions.jpg

Upvotes: 3

AdaTheDev
AdaTheDev

Reputation: 147374

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

Upvotes: 2

Related Questions