Python 等价于内联函数或宏 [英] Python equivalence to inline functions or macros

查看:23
本文介绍了Python 等价于内联函数或宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚意识到这样做

x.real*x.real+x.imag*x.imag

比做的快三倍

abs(x)**2

其中 x 是一个 numpy 复数数组.为了代码可读性,我可以定义一个像

where x is a numpy array of complex numbers. For code readability, I could define a function like

def abs2(x):
    return x.real*x.real+x.imag*x.imag

仍然比 abs(x)**2 快得多,但它是以函数调用为代价的.是否可以内联这样的函数,就像我在 C 中使用宏或使用内联关键字所做的那样?

which is still far faster than abs(x)**2, but it is at the cost of a function call. Is it possible to inline such a function, as I would do in C using macro or using inline keyword?

推荐答案

是否可以内联这样的函数,就像我在 C 中使用宏或使用内联关键字所做的那样?

Is it possible to inline such a function, as I would do in C using macro or using inline keyword?

没有.在到达这个特定指令之前,Python 解释器甚至不知道是否有这样的函数,更不用说它的作用了.

No. Before reaching this specific instruction, Python interpreters don't even know if there's such a function, much less what it does.

正如评论中所指出的,PyPy 将自动内联(以上仍然成立 - 它简单地"在运行时生成一个优化版本,从中受益,但在它失效时脱离它),尽管在这种特定情况下这无济于事,因为在 PyPy 上实施 NumPy 是在不久前开始的,而且直到今天还不是 beta 级别.但最重要的是:不要担心 Python 中这个级别的优化.实现要么自己优化,要么不优化,这不是你的责任.

As noted in comments, PyPy will inline automatically (the above still holds - it "simply" generates an optimized version at runtime, benefits from it, but breaks out of it when it's invalidated), although in this specific case that doesn't help as implementing NumPy on PyPy started only shortly ago and isn't even beta level to this day. But the bottom line is: Don't worry about optimizations on this level in Python. Either the implementations optimize it themselves or they don't, it's not your responsibility.

这篇关于Python 等价于内联函数或宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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