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?
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.