Sunday, November 18, 2018

Optimizing CPU with while loops

Using while loops are inevitable when listening to connections, waiting for keystrokes when it comes to me. But I faced high CPU consuming errors when using WHILE loops.

Even when you try a simple while loop such as,
while True:
    print "ok"

you will see significant CPU usage consuming. This happens because when there's while True it tries execute inside it as many as possible. In here printing ok.

To avoid this you need to use time.sleep(duration).

Rearrange the above code,
import time

while True:
    print "ok"
    time.sleep(0.005)

You can sleep very small time during while loop to avoid eating your CPU usage. Then we have limit the number of cycles this should run.