Edit: as @aix suggested, a better (more fair) way to compare the speed difference:
In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop
In [2]: from math import fabs
In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop
In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop
In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop
In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop
In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop
In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop
In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop
So it seems abs()
only has slight speed advantage over fabs()
for integers. For floats, abs()
and fabs()
demonstrate similar speed.
In addition to what @aix has said, one more thing to consider is the speed difference:
In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop
In [2]: import math
In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop
So abs()
is faster than math.fabs()
.
abs
works with far more than just integers and floats, and the result type is not always the same as the argument, e.g.abs(3+4j)
. – agf May 27 '12 at 7:24fabs
taking longer due to its always-float nature and you've got the right answer! – Patrick Perini May 27 '12 at 7:25__builtin__.abs()
be successfully applied to? – NPE May 27 '12 at 7:31__abs__
magic method – agf May 27 '12 at 17:59