Sadikov
Sadikov

Reputation: 147

Speeding up numpy small function

This small function is called multiple times in an application and runs really slow compared to the same code implementation in Matlab. There it works maybe as much as 10-100 times faster in so I was wondering where can it be improved in python/numpy.

def ahamming(n,mid):
    data = np.zeros(n)
    wid1 = mid - 1
    wid2 = n - mid
    wid = max(wid1,wid2)

    for i in range(n):
        arg = (i+1) - mid;
        data[i] = np.cos((np.pi*arg)/wid);
    return 0.54 + 0.46*data

Upvotes: 2

Views: 169

Answers (2)

zaxishere
zaxishere

Reputation: 186

Numpy implementation can offer some hints from docs.

## reference numpy implementation linked above
def hamming(M):
    if M < 1:
        return array([])
    if M == 1:
        return ones(1, float)
    n = arange(0, M)
    return 0.54 - 0.46*cos(2.0*pi*n/(M-1)) # of importance

Upvotes: 2

offeltoffel
offeltoffel

Reputation: 2801

This is an easy one for vectorization. The good thing when working with numpy arrays is that you can avoid loops and make use of numpy's speed.

You can substitute the loop as follows:

def ahamming(n,mid):
    data = np.zeros(n)
    wid1 = mid - 1
    wid2 = n - mid
    wid = max(wid1,wid2)

    i = np.arange(n)
    arg = (i+1) - mid
    data = 0.54 + 0.46*np.cos((np.pi*arg)/wid)

    return data

Slightly more efficient, but maybe less intuitive is

i = np.arange(1, n+1)
arg = i - mid

Edit: Speed results are in. Your loop-version with n = 500 takes 3.97 sec for 10000 calculations. The numpy version tool 0.10 sec which is faster by factor 40.

Upvotes: 5

Related Questions