Couple of newbie questions...

David Bolen db3l at fitlinxx.com
Fri Jul 27 05:20:33 CEST 2001


foobarickknob at yahoo.com (Scott Taylor) writes:

> I'm just getting started w/ Python - and have run into a couple issues
> w/ the Windows extensions...
> 
> 1) time.sleep doesn't seem to release time back to the Win32
> subsystem.  I had a tight loop, and CPU was maxed out at 100% even if
> I did a PumpWaitingMessages w/ a time.sleep.  To actually get the loop
> to return slices of time back to windows and not max out the CPU I had
> to do a PumpWaitingMessages followed by a win32api.Sleep(0) call.  My
> question is - shouldn't time.sleep actually make the process sleep w/o
> hogging CPU?

I've definitely used time.sleep() to yield within threads.  On
Windows, time.sleep() just directly calls the Win32 Sleep() function,
so I can't really think of a good reason why you'd see the
discrepancy.  Did you really just replace a call from time.sleep(0)
with win32api.Sleep(0) and have different behavior?  Could there have
been any other difference in the application when you were using time.

There is a minor difference that (at least in recent versions)
win32api.Sleep() actually uses the Win32 SleepEx() function beneath
the covers, but unless you pass in a second "bAlertable" parameter it
defaults to FALSE and should be equivalent to Sleep().

Note that Sleep(0) is a special case of yielding the current thread's
timeslice to any other equal priority thread in the process, but is
otherwise equivalent to no delay at all.  So if you have no other
higher or equal priority threads in your process, time.sleep(0) or
win32api.Sleep(0) is almost a no-op.  I say almost because the Python
wrapping (either the time or win32api module) does release and re-grab
the Python interpreter lock across the call, so it's possible that
some other Python thread might slip in if it was blocked on the lock.

So if you want to be a bit fairer, make the delay non-zero but just
really tiny (say time.sleep(0.01)).

You can see this from the interactive interpreter - something like:

    >>> while 1:
    ...   time.sleep(0)
    ...

will peg CPU usage at 100% (machine still responsive, but that loop is
taking whatever CPU it can get), versus:

    >>> while 1:
    ...   time.sleep(0.01)
    ...

which barely nudges the CPU.

This is Windows kernel behavior, and not directly related to Python.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list