[英]Python: For loop Vs. Map
I am currently in the process of optimising the translation part of my software, which translates co-ordinates x
amount of times. 我目前正在优化我的软件的翻译部分,这可以转换坐标
x
次。 My current translation code is in the translate
function and the supposedly optimised portion in the translate_map
function. 我当前的翻译代码是在
translate
的功能,并在所谓的优化部分translate_map
功能。
I read here that the map
function should be used instead of for
loops where possible because the loop is performed in C. 我在这里读到应该使用
map
函数而不是for
循环,因为循环是在C中执行的。
When I run a test case below, the map
function actually runs slower than a standard for
loop. 当我运行下面的测试情况下,
map
函数实际上运行速度比标准更慢for
循环。 Why does the map
perform slower than the conventional for
loop? 为什么
map
执行速度比传统的for
循环慢? How could I optimise the translate function to run faster? 如何优化translate功能以更快地运行?
import time
def translate(atom_list):
for i in atom_list:
i[1]+=1
i[2]+=1
i[3]+=1
atoms = [[1,1,1,1]]*1000
start = time.time()
for x in xrange(10000):
translate(atoms)
print time.time() - start
atoms = [[1,1,1,1]]*1000
start = time.time()
def translate_map(atom_list):
atom_list[1]+=1
atom_list[2]+=1
atom_list[3]+=1
for x in xrange(10000):
map(translate_map,atoms)
print time.time() - start
output: 输出:
2.92705798149
4.14674210548
I suspect most of the overhead you're seeing with your map
implementation comes from function call overhead. 我怀疑你在
map
实现中看到的大部分开销来自函数调用开销。 The translate
function does all its work within a single loop, so there's just a single function call for the whole process. translate
函数在一个循环中完成所有工作,因此对整个过程只有一个函数调用。 The implementation with map
makes a separate function call for every item in the list. 使用
map
的实现为列表中的每个项目进行单独的函数调用。
A second source of overhead (though I suspect it is small compared to the function calls) is that map
creates a list with the return values from the function. 第二个开销来源(虽然我怀疑它与函数调用相比较小)是
map
创建一个包含函数返回值的列表。 Since translate_map
doesn't have a return
statement, this will be all None
values. 由于
translate_map
没有return
语句,因此这将是None
值。 Note that in Python 3, map
is a generator, so your map
version won't work at all unless you iterate over the results from the map
call. 请注意,在Python 3中,
map
是一个生成器,因此除非您迭代map
调用的结果,否则您的map
版本将无法工作。 The explicit loop is much clearer though, so I'd stick with that (if you don't go for numpy). 显式循环虽然更清晰,但我坚持这一点(如果你不去寻找numpy)。
Oh, yes, numpy
would make this much easier (and almost certainly faster too): 哦,是的,
numpy
会让这更容易(而且几乎肯定也更快):
def translate(arr): # arr should be a numpy array
arr += 1
That's it! 而已! No loops needed (at the Python level).
不需要循环(在Python级别)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.