[Numpy-discussion] slow numpy.clip ?

David Cournapeau david at ar.media.kyoto-u.ac.jp
Mon Dec 18 02:17:08 EST 2006


Hi,

    When trying to speed up some matplotlib routines with the matplotlib 
dev team, I noticed that numpy.clip is pretty slow: clip(data, m, M) is 
slower than a direct numpy implementation (that is data[data<m] = m; 
data[data>M] = M; return data.copy()). My understanding is that the code 
does the same thing, right ?

    Below, a small script which shows the difference (twice slower for a 
8000x256 array on my workstation):

import numpy as N

#==========================
# To benchmark imshow alone
#==========================
def generate_data_2d(fr, nwin, hop, len):
    nframes = 1.0 * fr / hop * len
    return N.random.randn(nframes, nwin)

def bench_clip():
    m   = -1.
    M   = 1.
    # 2 minutes (120 sec) of sounds @ 8 kHz with 256 samples with 50 % 
overlap
    data    = generate_data_2d(8000, 256, 128, 120)

    def clip1_bench(data, niter):
        for i in range(niter):
            blop    = N.clip(data, m, M)
    def clip2_bench(data, niter):
        for i in range(niter):
            data[data<m]    = m
            data[data<M]    = M
            blop    = data.copy()

    clip1_bench(data, 10)
    clip2_bench(data, 10)

if __name__ == '__main__':
    # test clip
    import hotshot, hotshot.stats
    profile_file    = 'clip.prof'
    prof    = hotshot.Profile(profile_file, lineevents=1)
    prof.runcall(bench_clip)
    p = hotshot.stats.load(profile_file)
    print p.sort_stats('cumulative').print_stats(20)
    prof.close()

    cheers,

    David



More information about the NumPy-Discussion mailing list