[Tutor] line class

John Fouhy john at fouhy.net
Wed Jul 9 04:11:48 CEST 2008


On 09/07/2008, Paul McGuire <ptmcg at austin.rr.com> wrote:
> > def length(self):
>  >      dx,dy = self.p1 - self.p2
>  >      return (dx**2 + dy **2) ** 0.5
>
> How about:
>
>  def length(self):
>      return math.hypot( *(self.p1 - self.p2) )
>
>  Compiled C code will be much faster than squaring and square rooting.

Well, here's what I get:

Morpork:~ repton$ python -m timeit -s 'dx, dy = (8, 5)' '(dx**2 + dy**2)**0.5'
1000000 loops, best of 3: 0.555 usec per loop
Morpork:~ repton$ python -m timeit -s 'dx, dy = (8, 5)' -s 'import
math' 'math.hypot(dx, dy)'
1000000 loops, best of 3: 0.6 usec per loop

YMMV, but it doesn't make a strong case for "much faster".

(if I make a local reference to math.hypot, I can save 0.1 usec, which
puts the math.hypot technique in the lead, at the expense of
readability:

Morpork:~ repton$ python -m timeit -s 'dx, dy = (8, 5)' -s 'import
math' -s 'hyp = math.hypot' 'hyp(dx, dy)'
1000000 loops, best of 3: 0.501 usec per loop
)

-- 
John.


More information about the Tutor mailing list