Alex Rivera | Logout

How to occupy 80% CPU consistently?

Asked 2011-08-28T16:41:09.970
16

I'm looking for a way to occupy exactly 80% (or any other number) of a single CPU in a consistent manner.
I need this for some unit test that tests a component that triggers under specific CPU utilization conditions
For this purpose I can assume that the machine is otherwise idle.

What's a robust and possibly OS independent way to do this?

Edit
Report

1 Answer

17

There is no such thing as occupying the CPU 80% of the time. The CPU is always either being used, or idle. Over some period of time, you can get average usage to be 80%. Is there a specific time period you want it to be averaged over? This pseudo-code should work across platforms and over 1 second have a CPU usage of 80%:

while True:
    startTime = time.now()
    while date.now() - startTime < 0.8:
        Math.factorial(100) // Or any other computation here
    time.sleep(0.2)
answered 2011-08-28T16:49:00.900

Your Answer