强制将python函数内联到其调用站点
atinline的Python项目详细描述
这是一个python技巧,允许您在 与在C中一样,通过内联可以节省函数调用的成本 函数在调用位置的代码。当然,身为Python, 内联在运行时完成。
警告:不要在任何真正的代码中使用它。说真的。这只是一个有趣的黑客。
现在,假设您有这样的代码:
def calculate(x): return 3*x*x - 2*x + (1/x) def aggregate(items): total = 0 for item in items: total += calculate(item) return total
此代码为集合中的每个项支付函数调用的开销。 您可以通过内联这样的calculate函数来获得实质性的加速:
def aggregate(items): total = 0 for x in items: total += 3*x*x - 2*x + (1/x) return total
但现在你要为代码质量和重用付出代价。得到 这两个世界中最好的只是声明calculate函数应该是 内联:
from atinline import inline @inline def calculate(x): return 3*x*x - 2*x + (1/x) def aggregate(items): total = 0 for item in items: total += calculate(item) return total
现在,第一次运行aggregate()函数时,它将检测到 calculate()函数应该是内联的,进行必要的字节码破解 这样做,然后继续前进。对aggregate()的任何后续调用 将避免许多函数调用的开销。
目前只支持对顶级函数的普通调用;不会 如果您尝试内联方法,在dict中查找的函数, 或者其他类似的东西。它也不适用于关键字参数。 这些限制将来可能会消失。
字节码再生的繁重工作是由奇妙的“byteplay”完成的 模块,这是Atinline唯一的依赖项。