Search code examples
pythonpython-2.7cpucpu-usageinstructions

Wasting cycles with actual arbitrary instructions with Python


I have been working on a project in which I need to create a Python application that wastes instructions & cycles at this stage. Normally when 'cycle wasting' means waiting or sleeping; but I want to do it in a different manner. There should be some dummy instructions which wastes cycles even though the iteration period of the outer program loop is pretty high.

As an example (typical way to do it):

while(True):
    #..do simple thing..
    time.sleep(0.000001)

What I want to do:

while(True):
    #..do complex instructions..
    time.sleep(0.2)

With the first 'typical' example I am able to achieve custom CPU loads such as 25% or 100% by simply adjusting the sleeping period. I want to be able to do the same with the second code, where the period is a pretty high value and is constant, but the instructions are complex and dynamic.

Please keep in mind that I have to do this as a Python application and not as a bash script that runs from shell.

Is there a way to achieve this? Any help will be greately appreciated.

Thanks in advance.

Note: I apologize if there is a wrong tag.

Edit: Using Python 2.7

Edit: The application requires that there should be a periodic sleep, such as time.sleep(2), time.sleep(0.2). This is kind of our restriction.


Solution

  • Didn't think about the best way, just tried something, its 100% CPU on my laptop i5. I go for random matrix generation and product:

    def cpu_load():
        import numpy as np
        while True:
        a = np.random.random([1000, 1000])
        b = np.random.random([1000, 1000])
        c = np.mean(a*b)