I am trying to calculate some values using numpy. Here is my code,

x= np.zeros([nums])
for i in range (nums):    
    x[i] = np.mean((Zs[i :] -  Zs[:len(Zs)-i]) ** 2)

The code runs perfectly and give desired result. But it takes very long time for a large number nums value. Because the Zs and numsvalue having same length. Is it possible to use some other method or multiprocessing to increase the speed of calculation?

  • 2
    \$\begingroup\$ How are you sure that this is where the code is slow? Have you profiled the entire program? For us to help you optimize the code we need to understand more about what the code does. \$\endgroup\$
    – pacmaninbw
    Apr 30, 2021 at 13:27

1 Answer 1


Minor style edits

Like you said, the code seems to be perfectly fine and I don't see a very obvious way to make it faster or more efficient, as the consecutive computations you are making in your for loop don't seem to be easy to relate to one another.

Of course this is just my input after thinking for some time, other people may have clever suggestions I can't come up with.

However, I would make minor edits to your code, for the sake of homogenisation:

x = np.zeros(Zs.shape)
for i in range(len(Zs)):    
    x[i] = np.mean((Zs[i:] - Zs[:-i])**2)

For the snippet of code we have, it is not clear the relationship between nums and Zs and so it makes more sense to have the loop in terms of Zs.

Also, notice that the right term of the subtraction I replaced Zs[:len(Zs)-i] with Zs[:-i], which is a nice feature of Python that is worth getting used to, you can learn about using negative indices in Python.

Other minor things were just fixing spacing. If you want, take a look at the PEP 8 style guide for Python :)

  • \$\begingroup\$ thank you for your comment. Zs and nums having the same length so using that range in for loop are perfectly fine. \$\endgroup\$
    – Tanvir
    Apr 24, 2021 at 8:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.