In [55]: %%timeit
...: x = list(range(1000))
...: A, B, i = 0, 0, 0
...: while i < len(x):
...: if A > 5:
...: A += x[i]
...: B = min(B, A / 2)
...: else:
...: A -= x[i]
...: i += 1
...:
315 µs ± 6.75 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
Replacing the while
with a for
gives a noticeable increase:
In [57]: %%timeit
...: x = list(range(1000))
...: A, B, i = 0, 0, 0
...: for i in range(len(x)):
...: if A > 5:
...: A += x[i]
...: B = min(B, A / 2)
...: else:
...: A -= x[i]
143 µs ± 318 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
And a bit better with direct iteration on x
:
In [59]: %%timeit
...: x = list(range(1000))
...: A, B = 0, 0
...: for v in x:
...: if A > 5:
...: A += v
...: B = min(B, A / 2)
...: else:
...: A -= v
...:
121 µs ± 324 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
In the right cases, list comprehension can further streamline the loop - but not here.
numpy
vectorize makes use of compiled numpy methods, and numpy specific storage. np.vectorize
clearly states it is not a performance tool. For large arrays it can improve on the speed of a list comprehension by a bit. But it's no use here, for the same reason a list comprehension doesn't work.
There aren't any other ways of 'streamlining' python loops.