code optimization (calc PI) / Full Code of PI calc in Python and C.

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Jan 3 21:00:38 EST 2007


Michael M.:
> * The C is very fast, Python not.
> * Target: Do optimization, that Python runs nearly like C.

Python can't be fast as C for that kind of programs.
Note that your original C program gives less digits than the Python
program.
Your original takes about ~15.2 s on my PC. The following version (I
have just cleaned it up a bit, probably it can be improved) needs about
~0.7 seconds with Psyco and ~5.7 s without (Psyco compilation time and
Python startup times aren't included, if you include them the timings
are ~0.94 s and ~5.96 s).
Compiled with ShedSkin this program needs ~0.29 s (redirecting the
output to a file, because ShedSkin printing is slow still).


from time import clock

def compute_pi():
    pi = []
    a = 10000
    b = d = e = g = 0
    c = 5600
    f = [2000] * (c + 4000 + 1)
    while c:
       d = 0
       g = c * 2
       b = c
       while b > 1:
         d += f[b] * a
         g -= 1
         f[b] = d % g
         d = d // g
         g -= 1
         d *= b
         b -= 1
       c -= 14
       pi.append("%04d" % int(e + d // a))
       e = d % a
    return "".join(pi)

import psyco; psyco.bind(compute_pi)
start_time = clock()
print compute_pi()
print "Total time elapsed:", round(clock() - start_time, 2), "s"

Bye,
bearophile




More information about the Python-list mailing list