views:

608

answers:

5

Hello,

I'm looking to test system responsiveness etc. on a few machines under certain CPU usage conditions. Unfortunately I can only create ~100% usage (infinite loop) or not enough CPU usage (I'm using C#).

Is there any way, in rough approximation, as other tasks are running on the system as well, to create CPU usage artificially at 20, 30, 40% (and so forth) steps?

I understand that there are differences between systems, obviously, as CPU's vary. It's more about algorithms/ideas on customizable CPU intensive calculations that create enough usage on a current CPU without maxing it out that I can tweak them then in some way to adjust them to create the desired percentage.

A: 

Not done this - but you could try working out prioritised threads running in multiple programs.

Preet Sangha
A: 

When you tried using sleep, did you do like this or just put the sleep inside the actual loop? I think this will work.

while(true)
{
  Thread.Sleep(0);
  for(int i=0;i<veryLargeNumber; i++)
  {
      //maybe add more loops here if looping to veryLargeNumber goes to quickly
      //also maybe add some dummy operation so the compiler doesn't optimize the loop away
  }
}
+3  A: 
Colin Gravill
+5  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.

I would probably use C# to 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
+3  A: 

This then?

    DateTime lastSleep = DateTime.Now;            
    while (true)
    {
        TimeSpan span = DateTime.Now - lastSleep;
        if (span.TotalMilliseconds > 700)
        {
            Thread.Sleep(300);
            lastSleep = DateTime.Now;
        }
    }

You could use smaller numbers to get a more steady load....as long as the ratio is whatever you want. This does only use one core though, so you might have to do this in multiple threads.

Bubblewrap