Python For Loop Slowing With Time Python For Loop Slowing With Time python-3.x python-3.x

Python For Loop Slowing With Time


This is another case of "need more information". However, Python has a standard way of constructing nested loops like this efficiently, itertools.product:

from itertools import productfor x, y, z in product(xrange(xs), xrange(zs), xrange(ys)):    vp = [x * vs, y * vs, z * vs]    v = Cube(vp)

It doesn't require the construction of ranges every time in the inner loop. I also switched your use of range to xrange, as it's better for large ranges, although this is really irrelevant with product.

@JohnZ's question is good -- if your "predetermined size values" are very large, and especially if vs is also large, you could be constructing some large values, and it could be taking a long time for Cube to process them.

I doubt the loop itself is slowing down, but the numbers are getting larger, so your calculations might be.


Three things I can think of:

Memory - if you're storing all of the generated values somewhere, the loop might be slowing down because the of all the memory being used. Python has it's own memory manager, so using up lots of memory could eventually make the program slower.

Complexity of calculations - Python uses arbitrary precision numeric data types. If you are multiplying extremely large numbers together (especially floats) the program will slow down. It really depends on how large these values get.

Cube - It could be a bug in the Cube code (although I'm sure it's probably just as simple as it sounds).