Peter Maas: > I have noticed that in the language shootout at shootout.alioth.debian.org > the Python program for the n-body problem is about 50% slower than the Perl > program. This is an unusual big difference. I tried to make the Python program > faster but without success. Has anybody an explanation for the difference? > It's pure math so I expected Perl and Python to have about the same speed.
I don't have a good answer for you, but if you profile that code you find that most of the running time is used here, in this nested loop: for j in xrange(i + 1, nbodies): b2 = bodies[j] dx = b_x - b2.x dy = b_y - b2.y dz = b_z - b2.z distance = sqrt(dx*dx + dy*dy + dz*dz) aux = dt / (distance*distance*distance) b_mass_x_mag = b_mass * aux b2_mass_x_mag = b2.mass * aux b.vx -= dx * b2_mass_x_mag b.vy -= dy * b2_mass_x_mag b.vz -= dz * b2_mass_x_mag b2.vx += dx * b_mass_x_mag b2.vy += dy * b_mass_x_mag b2.vz += dz * b_mass_x_mag If you are using Python you can use Psyco, it helps a lot (473 s instead of 2323 s, against 1622 s for the Perl version): http://shootout.alioth.debian.org/sandbox/benchmark.php?test=nbody&lang=all If you need speed, you can also use ShedSkin that compiles this Python program producing an executable essentially fast as the C++ version (about 16 s on the same computer, the Shootout autor isn't going to add ShedSkin to the language list yet). Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list