I just realized that doing
x.real*x.real+x.imag*x.imag
is three times faster than doing
abs(x)**2
where x
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.