How to increase the speed of this program?

John Machin sjmachin at lexicon.net
Tue Nov 28 06:53:06 EST 2006


Peter Otten wrote:
> Peter Otten wrote:
>
> > Leo Kislov wrote:
> >
> >>
> >> Peter Otten wrote:
> >>> Peter Otten wrote:
> >>>
> >>> > HYRY wrote:
> >>> >
> >>> >> 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.
> >>> >
> >>> >> oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1
> >>> >
> >>> > ITEMSIZE = 2
> >>> > size = ITEMSIZE*(len(larray) + len(rarray))
> >>> > oarray = array.array("h")
> >>> > oarray.fromstring("\0" * size)
> >>> >
> >>> > may be a bit faster.
> >>>
> >>> Confirmed:
> >>>
> >>> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a =
> >>> array("h"); a.fromstring("\0"*(2*N))'
> >>> 100 loops, best of 3: 9.68 msec per loop
> >>> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a =
> >>> array("h",
> >>> [0]*N);'
> >>> 10 loops, best of 3: 199 msec per loop
> >>
> >> Funny thing is that using huge temporary string is faster that
> >> multiplying small array:
> >>
> >> C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a
> >> =array('h'); a.fromstring('\0'*(2*N))"
> >> 100 loops, best of 3: 9.57 msec per loop
> >>
> >> C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a
> >> = array('h','\0\0'); a*N"
> >> 10 loops, best of 3: 28.4 msec per loop
> >>
> >> Perhaps if array multiplication was as smart as string multiplication
> >> then array multiplication version would be the fastest.
>
> Oops, I have to work on my reading skills. You're right, of course...
>
> > That will not suffice:
> >
> > $ python2.5 -m timeit -s'from array import array; from itertools import
> > repeat; N = 10**6; init = [0]*N' 'array("h", init)'
> > 10 loops, best of 3: 130 msec per loop
> >
> > $ python2.5 -m timeit -s'from array import array; from itertools import
> > repeat; N = 10**6; init = "\n"*(2*N)' 'array("h").fromstring(init)'
> > 100 loops, best of 3: 5 msec per loop
> >
> > A big chunk of the time is probably consumed by "casting" the list items.
> > Perhaps an array.fill(value, repeat) method would be useful.
>
> ... and that could be spelled array.__mul__ as you suggest.
>

I'm extremely agnostic about the spelling :-) IOW I'd be very glad of
any way [pure Python; e.g. maintaining my own version of the array
module doesn't qualify] to simply and rapidly create an array.array
instance with typecode t and number of elements n with each element
initialised to value v (default to be the zero appropriate to the
typecode).

Cheers,
John




More information about the Python-list mailing list