Python是否会优化循环中的函数调用? [英] Does Python optimize function calls from loops?

查看:124
本文介绍了Python是否会优化循环中的函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个代码从循环中调用了数百万次的某些函数,并且我希望代码更快:

Say, I have a code which calls some function millions time from loop and I want the code to be fast:

def outer_function(file):
    for line in file:
        inner_function(line)

def inner_function(line):
    # do something
    pass

不一定是文件处理,例如可以是从函数绘制线调用的函数绘制点。这个想法是在逻辑上必须将两者分开,但是从性能的角度来看,它们应该尽可能快地协同工作。

It's not necessarily a file processing, it could be for example a function drawing point called from function drawing line. The idea is that logically these two have to be separated, but from performance point of view they should act together as fast as possible.

Python是否会自动检测并优化这些东西? ?如果不是,是否有办法提供线索?也许使用一些额外的外部优化器?...

Does Python detects and optimizes such things automatically? If not - is there a way to give it a clue to do so? Use some additional external optimizer maybe?...

推荐答案

Python不内联函数调用,因为它具有动态特性。从理论上讲, inner_function 可以做一些将名称 inner_function 重新绑定到其他事情的工作-Python无法知道编译时可能会发生这种情况。例如:

Python does not inline function calls, because of its dynamic nature. Theoretically, inner_function can do something that re-binds the name inner_function to something else - Python has no way to know at compile time this might happen. For example:

def func1():
    global inner_func
    inner_func = func2
    print 1

def func2():
    print 2

inner_func = func1

for i in range(5):
    inner_func()

打印:

1
2
2
2
2

您可能认为这太可怕了。然后,再想一想-Python的功能和动态特性是其最吸引人的功能之一。 Python允许的许多功能都以性能为代价,在大多数情况下,这是可以接受的。

You may think this is horrible. Then, think again - Python's functional and dynamic nature is one of its most appealing features. A lot of what Python allows comes at the cost of performance, and in most cases this is acceptable.

也就是说,您可以使用< href = http://code.google.com/p/byteplay/ rel = noreferrer> byteplay 或类似的方法-将内部函数反汇编为字节码,然后将其插入外部函数,然后重新组装。再次考虑一下,如果您的代码对性能至关重要,足以引起此类黑客攻击,则只需用C对其进行重写。Python为FFI提供了不错的选择。

That said, you can probably hack something together using a tool like byteplay or similar - disassemble the inner function into bytecode and insert it into the outer function, then reassemble. On second thought, if your code is performance-critical enough to warrant such hacks, just rewrite it in C. Python has great options for FFI.

这都与官方的CPython实现有关。理论上,运行时调适的解释器(例如PyPy或可悲的已解散的Unladen Swallow)可以检测到正常情况并执行内联。 las,我对PyPy还不够熟悉,无法知道它是否可以这样做,但是绝对可以。

This is all relevant to the official CPython implementation. A runtime-JITting interpreter (like PyPy or the sadly defunct Unladen Swallow) can in theory detect the normal case and perform inlining. Alas, I'm not familiar enough with PyPy to know whether it does this, but it definitely can.

这篇关于Python是否会优化循环中的函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆