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

查看:75
本文介绍了等效于内联函数或宏的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天全站免登陆