Python equivalence to inline functions or macros

前端 未结 6 2251
天涯浪人
天涯浪人 2020-12-04 15:44

I just realized that doing

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

is three times faster than doing

abs(x)**2

where x

6条回答
  •  -上瘾入骨i
    2020-12-04 16:11

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

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

    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.

提交回复
热议问题