How to increase the speed of this program?

Paul McGuire ptmcg at austin.rr._bogus_.com
Tue Nov 28 09:21:30 CET 2006


"HYRY" <zhangry at feng.co.jp> wrote in message 
news:1164699156.682944.97410 at j44g2000cwa.googlegroups.com...
>I want to join two mono wave file to a stereo wave file by only using
> the default python module.
> Here is my program, but it is much slower than the C version, so how
> can I increase the speed?
> I think the problem is at line #1, #2, #3.
>
I'm not overly familiar with the array module, but one place you may be 
paying a penalty is in allocating the list of 0's, and then interleaving the 
larray and rarray lists.

What if you replace lines 1-3 with:

def takeOneAtATime(tupleiter):
    for i in tupleiter:
        yield i[0]
        yield i[1]

oarray = array.array("h",takeOneAtATime(itertools.izip(larray,rarray)))

Or in place of calling takeOneAtATime, using itertools.chain.

oarray = array.array("h", itertools.chain(*itertools.izip(larray,rarray)))

Use itertools.izip (have to import itertools somewhere up top) to take left 
and right values in pairs, then use takeOneAtATime to yield these values one 
at a time.  The key though, is that you aren't making a list ahead of time, 
but a generator expression.  On the other hand, array.array may be just 
building an internal list anyway, so this may just be a wash.

Also, try psyco, if you can, especially with this version.  Or pyrex to 
optimize this data-interleaving.

HTH,
-- Paul





More information about the Python-list mailing list