Leibniz_Pi.py

David Mertz, Ph.D. mertz at gnosis.cx
Fri Oct 11 13:56:08 EDT 2002


|Using 1 million terms as an input argument, the Java version is a bit
|faster, which I think is expected ...
|     Java SDK 1.4 .......  ~ 3-4   seconds
|    Python 2.2.1 .........  ~ 9-10 seconds
|----------------------------------------------------------------
|    Leibniz_Pi.py
|    Pi = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 ... )

Well, first thing of course is that the whole program is a bit
pointless.  Leibniz' algorithm is a very long way from being the
currently most efficient means of calculating Pi. And algorithm
efficiency is almost always more important than program tweaks.
Moreover, I'm pretty sure that by a million terms you're extremely lossy
using FP approximations of fractions.

In other words, don't try this at home :-).

Nonetheless, my article on Psyco recently appeared at:

    http://www-106.ibm.com/developerworks/linux/library/l-psyco.html

So it got me thinking about the above language benchmarks.  It's
actually pretty impressive that JRE 1.4 is optimizing that well, IMO.
So I decided to plug two extra lines into the posted program.  Namely
'import psyco' and 'psyco.bind(calculate_pi)'.  Well, I added a better
timer too, using 'time.clock()', but that's incidental.

It turns out that the two Psyco lines reduce running time by about 66%
(with 1M loops, presumably a better ratio with more loops).  Not bad for
two lines of code.  In fact, that probably makes Python+Psyco about the
same speed as JRE 1.4.  It makes me wonder if Python programmers
shouldn't start trying to import Psyco fairly routinely (in try/except
blocks that fail gracefully where Psyco is absent).

My thanks to Armin.

Yours, David...

--
    _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/
   _/_/    ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~  _/_/
  _/_/  The opinions expressed here must be those of my employer...   _/_/
 _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them!  _/_/





More information about the Python-list mailing list