Python Faster For Loop
Python Faster For Loop
Comparison and
Performance
This content was originally published at:
https://www.blog.duomly.com/loops-in-python-comparison-and-performance/
***
import random
r = [random.randrange(100) for _ in
range(100_000)]
import numpy as np
n = 1_000
x, y = random.sample(r, n), random.sample(r, n)
%%timeit
i, z = 0, []
while i < n:
z.append(x[i] + y[i])
i += 1
%%timeit
z = []
for i in range(n):
z.append(x[i] + y[i])
%%timeit
z = [x[i] + y[i] for i in range(n)
%%timeit
z = x_ + y_
%%timeit
z = x_ + y_
The output is:
814 ns ± 5.8 ns per loop (mean ± std.
dev. of 7 runs, 1000000 loops each)
The results obtained when n is larger,
that is 10_000 and 100_000 are shown in
the table below. They show the same
relationships, as in this case, with even
higher performance boost when using numpy.
Nested Loops
m, n = 100, 1_000
x = [random.sample(r, n) for _ in range(m)]
y = [random.sample(r, n) for _ in range(m)]
%%timeit
i, z = 0, []
while i < m:
j, z_ = 0, []
while j < n:
z_.append(x[i][j] + y[i][j])
j += 1
z.append(z_)
i += 1
%%timeit
z = []
for i in range(m):
z_ = []
for j in range(n):
z_.append(x[i][j] + y[i][j])
z.append(z_)
%%timeit
z = [[x[i][j] + y[i][j] for j in range(n)] for i
in range(m)]
%%timeit
z = x_ + y_
%%timeit
z = x_ + y_
Results Summary
This table summarizes the obtained
results:
Number of 1 1 1 100
elements, × × × ×
m × n 1K 10K 100K 1K
160
Python while µs
1.66 ms 17.0 ms 19.7 ms
122
Python for 1.24 ms 13.4 ms 16.4 ms
µs