« My New Blog | Main | Sometimes Being a Nerd is NOT_FUN_(aka.the_suck()) »

python performance suck

Stupid nerd trick:  (File under... DUH!)

When working on real-time audio control, it's probably not a bad idea to try to get the best possible time-slicing quantum possible.  What with latency to think about and generally wanting everything to just-happen-right-the-heck-now(TM)...

This can be taken a bit far, though.  Say, for instance, you fork a thread to respond to an event coming from an audio synthesis server and, to compound the fun, you forget that you're writing instructions for a computer.  You know, one of those things that does only and exactly what you tell it to do.  What happens?  You suck up every available clock cycle by writing an empty "while x!= this_event_thing: do nothing" loop.  This isn't so surprising in retrospect.  It's exactly what you're telling the computer to do!

How do we keep from spiking the processor while avoiding any appreciable latency?

We can put a time.sleep(0) (python) in there which will yield the cpu to any other >= priority thread.  This keeps the system responsive, but will still take every last available clock cycle. 

Being one who never wants to watch my powerbook melt through my desk (that G4 thing can get HOT),  there is another option.  Put a very short time.sleep() increment in there.  Right now I'm using this:

while self.theIncomingMessage is not "The expected Message":
   time.sleep(1./96000.)

Pretty much zero latency and no unnecessary processor spin.  Sweet.


I'm not the only one...

http://mail.python.org/pipermail/python-list/2001-July/056629.html

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.
http://www.codecomments.com/LabVIEW/message735053.html

http://www.thescripts.com/forum/thread30779.html

TrackBack

TrackBack URL for this entry:
http://www.jonathansaggau.com/blog/mt-tb.cgi/10

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)