Python equivalence to inline functions or macros

前端 未结 6 2254
天涯浪人
天涯浪人 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条回答
  •  渐次进展
    2020-12-04 15:58

    Actually it might be even faster to calculate, like:

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

    Thus, the extra cost of function call will likely to diminish. Lets see:

    In []: n= 1e4
    In []: x= randn(n, 1)+ 1j* rand(n, 1)
    In []: %timeit x.real* x.real+ x.imag* x.imag
    10000 loops, best of 3: 100 us per loop
    In []: %timeit x.real** 2+ x.imag** 2
    10000 loops, best of 3: 77.9 us per loop
    

    And encapsulating the calculation in a function:

    In []: def abs2(x):
       ..:     return x.real** 2+ x.imag** 2
       ..: 
    In []: %timeit abs2(x)
    10000 loops, best of 3: 80.1 us per loop
    

    Anyway (as other have pointed out) this kind of micro-optimization (in order to avoid a function call) is not really productive way to write python code.

提交回复
热议问题