Python While Loop CPU demanding
Question: I don't want to bother people here with a simple question and also tell that I
googled for information but I would like to get input from the people who as
faced the same. It is stated that while loops in python slow down
(<http://wiki.python.org/moin/WhileLoop>). I have a script which employs only
one loop but that is quite important and in fact it really slows down. My
first program was using 100 % CPU (Dual core!!!). I introduced a sleep()
function on the loop and the CPU usage went down to 50 %. I cannot just keep
increasing the sleep time, actually I would like to decrease it. Anyway, is
there any 'trick' to make this while loop faster?

(The condition is whether a button is pressed or not on a user interface build
on pyQt4)


Answer: The reference you linked to is misleading. The speed difference between the
two samples will be minimal and usually not even noticeable if any real work
is being done inside the loop.

It is the nature of _any_ loop that it will use 100% of its allocated time
until it's done. It doesn't matter if the loop is wickedly efficient or wildly
inefficient. The only way around this is to call some OS function that makes
it wait, such as the `sleep` that you tried.

The reason that modern OS GUI's are event driven is so that you don't have to
wait in a loop for an event - you call a single function to wait for a
message, and the OS gives the CPU to someone else until a message arrives.
With a framework such as Qt this will be buried in what's called a message
loop, and you'll need to provide the proper framework hooks to get the event
routed to your own function.

