Hacker News new | ask | show | jobs
by scg 5734 days ago
Here's a simple test for the curious. It's not a benchmark.

  import math
  num_primes = 0
  for i in xrange(2, 500000):
    if all(i % j for j in xrange(2, int(math.sqrt(i)) + 1)):
      num_primes += 1
  print num_primes
Here's the code above translated to C++ by Nuitka: http://pastebin.com/41ueyTEB

  # CPython 2.6.6
  $ time python hello.py 
  41538
  real	0m6.377s
  user	0m6.350s
  sys	0m0.020s

  # Nuitka & g++-4.5
  $ time ./hello.exe
  41538
  real	0m4.573s
  user	0m4.270s
  sys	0m0.300s
1 comments

i ran each test 3 times and picked the fastest. I shutdown all servers(mysql, apache), closed music player to minimize the system effect on the test.

Python:

    real    0m12.775s
    user    0m12.636s
    sys    0m0.037s
Nuitka:

    real	0m7.096s
    user	0m6.930s
    sys	0m0.093s
Lua:

    real	0m2.641s
    user	0m2.410s
    sys	0m0.010s
LuaJit:

    real	0m0.613s
    user	0m0.600s
    sys	0m0.000s
from experience experimenting with a toy scripting language where tried to make it as minimal as possible, essentially every operation was a function call so it just figured out what the right function was and called the corresponding function directly via a C++ function pointer. In the end it was slightly faster than LuaJit at doing some math for 100,000 times. It was a file with the same operation pasted 100,000 times which tested parsing speed... anyway...

TL;DR If you want to know why Python and Nuitka are so much slower, run the test through callgrind or something that reports the number of functions calls being made. You will find Python(possibly Nuitka as well) making billions of functions and allocations while lua's count in maybe a couple hundred million at most.

Also, I tested my Lua code converted to Python but it only shaved less than 1 second of fastest so no difference.

test.lua:

    local sqrt = math.sqrt
    num_primes = 0
    for i = 2, 500000 do
        n = 1
        for j = 2, sqrt(i) do
            if (i % j) == 0 then
                n = 0
                break
            end
        end
        num_primes = num_primes + n
    end
    print (num_primes)