[Tutor] continuous running of a method

Steven D'Aprano steve at pearwood.info
Wed Aug 25 12:37:54 CEST 2010


On Wed, 25 Aug 2010 03:25:12 pm Nitin Das wrote:
> The problem with this while loop is if your random value doesn't lie
> between the mentioned range then ur 100% cpu would be utilized. The
> one thing u can do is to sleep for some time lets say 0.5 sec after
> every while loop iteration , in this case ur cpu utilization will go
> down.

Pausing for half a second after each loop is WAY over-kill. Half a 
millisecond would be more appropriate, and even that is over-cautious.

Any modern multi-tasking operating system will ensure than a while loop 
doesn't kill your computer's responsiveness. A decent operating system 
will still remain responsive even at 100% CPU usage. Even Windows does 
that!

As I type this, I have about a dozen browser windows open, a music 
player playing, various text editors, a bittorrent client, and a Python 
interactive session running this:

>>> while 1:
...     pass 
...

(plus a whole heap more). Here are the top 4 entries according to top:

% CPU    Process name
96       python2.6
12       Xorg
 7       epiphany
 1       gtk-gnutella

Obviously this adds up to more that 100%. The load average is just 1.31. 
That's nothing -- a load less than 2 isn't even worth mentioning for a 
single CPU desktop machine. I don't start to worry until the load 
exceeds 3 or 4. I don't panic until it gets to 10 :)

This is perfectly normal, and nothing to be concerned about. I can 
barely notice any performance degradation despite the while loop. And 
of course Python itself remains responsive: type Ctrl-C kills it 
instantaneously.

You might need to worry this if you're writing in a low-level language 
like C, but in Python? Not unless you do something out of the ordinary, 
like setting the check interval to a ridiculously high value.

You can force Python to give even more time to threads by calling 
time.sleep(0). Other than that, you're not likely to need to care about 
this. Just write your code in the most straightforward way and leave 
the rest to Python and the OS.



-- 
Steven D'Aprano


More information about the Tutor mailing list