user2863620
user2863620

Reputation: 643

How to speed up this python code (conditional in loop)?

I try to find a way that does not use the if...else conditional in the loop so that speeds up the code, any idea?

for i in range(n):
    for j in range(n):
        if a1[i, j] == 0:
            b1[i, j] = 1
        else:
            b1[i, j] = a1 / np.sin(a1)
        if a2[i, j] == 0:
            b2[i, j] = 1
        else:
            b2[i, j] = a2 / np.sin(a2)

Upvotes: 1

Views: 395

Answers (2)

Warren Weckesser
Warren Weckesser

Reputation: 114921

You are computing the reciprocal of the sinc function. So you could do:

b1 = 1.0 / np.sinc(a1/np.pi)
b2 = 1.0 / np.sinc(a2/np.pi)

The numpy sinc function is vectorized, so you don't need to write the loops.

Upvotes: 8

Alejandro
Alejandro

Reputation: 3082

The if() statements are considered O(1) time operations , although a missed branch prediction may be costly if efficiency is of the essence (in which case, running for loops within Python code isn't the best choice).

Other than the possible missed branch predictions, the asymptotic time is, as @Keeler mentioned, O(n^2). Optimizing the code inside the for loop may help with some constant factors within the Big-Oh notation though, which turns out to be pretty fruitful in practice.

An optimization you could do is follow @Warren 's advice and use sinc()

Upvotes: 1

Related Questions