似乎在较大的
n
值下,
itertools.product
速度较慢:
In [24]: print _23
from itertools import product
def nested_loops(n):
for i in range(n):
for j in range(n):
for k in range(n):
pass
def itertools_product(n):
for (i,j,k) in product(range(n), repeat=3):
pass
In [25]: %timeit nested_loops(128)
10 loops, best of 3: 68.6 ms per loop
In [26]: %timeit itertools_product(128)
10 loops, best of 3: 162 ms per loop
In [27]: %timeit nested_loops(10)
10000 loops, best of 3: 84.5 us per loop
In [28]: %timeit itertools_product(10)
10000 loops, best of 3: 79.8 us per loop
In [30]: %timeit nested_loops(300)
1 loops, best of 3: 833 ms per loop
In [31]: %timeit itertools_product(300)
1 loops, best of 3: 2.07 s per loop
不使用元组拆包:
In [40]: print _39
from itertools import product
def itertools_product(n):
for ijk in product(range(n), repeat=3):
pass
In [41]: %timeit itertools_product(128)
10 loops, best of 3: 115 ms per loop
In [42]: %timeit itertools_product(10)
10000 loops, best of 3: 59.2 us per loop
In [43]: %timeit itertools_product(300)
1 loops, best of 3: 1.47 s per loop
此外,出于好奇,使用列表推导和生成器表达式:
def list_comprehension_product(n):
range_n = range(n)
for (i,j,k) in [ (i, j, k) for i in range_n for j in range_n for k in range_n ]:
pass
def generator_expression_product(n):
range_n = range(n)
for (i,j,k) in ( (i, j, k) for i in range_n for j in range_n for k in range_n ):
pass
In [51]: %timeit list_comprehension_product(128)
1 loops, best of 3: 583 ms per loop
In [52]: %timeit generator_expression_product(128)
1 loops, best of 3: 480 ms per loop
这些基准测试是在 python --version
下运行的:
2.6.7 (r267:88850, Jul 31 2011, 19:30:54)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)]
itertools.product()
的想法是为了加速嵌套的for循环。 - Sven Marnach