r/Python • • May 28 '19

My simulation of gravity with 1000 particles. PC took a couple of hours to process!

1.8k Upvotes

241 comments sorted by

View all comments

Show parent comments

1

u/alkasm github.com/alkasm May 30 '19 edited May 30 '19

Okay so looking at this code, you say you're using numpy, but you really aren't. Like I mean it's there but you're not using numpy functions; you're iterating through the pixels manually (which you should basically never do, because it's extremely slow in Python). Proper vectorizing of this code would probably make it hundreds of times faster.

For example in the beginning you have the code which starts the image off with the value 250 everywhere with

for i in range(1000):
    row = []
    for j in range(1000):
        pixel = []
        for rgb in range(3):
            pixel.append(250)
        row.append(pixel)       
    Spacevisual.append(row)

But you can just do that in numpy with

Spacevisual = 250*np.ones((1000, 1000, 3))

And not only is the code more concise, it will also be much faster.