2

Possible Duplicate:
Simulate steady CPU load and spikes

I need to write an application that can simulate high cpu-usage at a pre-set values ( e.g., 30%, 50%, 90% etc) for a certain duration. Meaning it will take two inputs (CPUUsage and duration). Let say i use 50% for CPU-Usage and 2 minutes for Duration). This mean that when I run the application, it should take 50% CPU for 2 minutes. Any ideas how this can be achieved?

Community
  • 1
  • 1
imak
  • 6,489
  • 7
  • 50
  • 73
  • There are lots of ways to take 50% CPU for 2 minutes. Busy loop for 1 minute, sleep for 1 minute. Or busy loop for 1s, sleep for 1s. And what about memory usage? Presumably you are trying to replicate a real program. That will be exercising memory too presumably. Any chance of telling us what the problem is? – David Heffernan Jan 23 '12 at 20:16
  • 3
    http://stackoverflow.com/a/2514697/284240 – Tim Schmelter Jan 23 '12 at 20:17

1 Answers1

2

You will need to write a spin loop to keep the processor busy for the amount of time desired. Sleep(n) won't work because while it keeps your thread busy it allows the CPU to do something else.

Use a thread-based timer (not a message based timer) to schedule regular execution of your load simulator function, say, every 10 seconds. In that function, run your spin loop (a for loop that increments a local variable) until the desired load time (% of 10 seconds) is reached, then exit the function. The timer will call you again in (about) 10 seconds to chew up another timeslice. So, for 30% load, your spin loop should churn for 3 seconds out of each 10 second interval.

You should also consider the number of executable cores that are present in your system. On a quad core hyperthreaded Intel processor, you should create 8 threads and run your load simulator in each thread.

dthorpe
  • 35,318
  • 5
  • 75
  • 119