Why is equivalent Python code so much slower

前端 未结 4 1680
情歌与酒
情歌与酒 2020-12-15 19:09

can somebody explain why is the following trivial code (implementation of Euclid\'s algorithm to find greatest common denominator) about 3 times slower then equivalent code

4条回答
  •  离开以前
    2020-12-15 19:51

    I can confirm that ruby1.9 is faster than CPython for this "microbenchmark" on my machine:

    | Interpreter                     | Time, s | Ratio |
    |---------------------------------+---------+-------|
    | python-2.6 (cython_gcd.gcd_int) |     2.8 |  0.33 |
    | pypy-1.4                        |     3.5 |  0.41 |
    | jython-2.5 (java "1.6.0_20")    |     4.7 |  0.55 |
    | python-2.6 (cython_gcd.gcd)     |     5.6 |  0.65 |
    | ruby-1.9                        |     8.6 |  1.00 |
    | jython-2.5                      |     8.9 |  1.03 |
    | python-3.2                      |    11.0 |  1.28 |
    | python-2.6                      |    15.9 |  1.85 |
    | ruby-1.8                        |    42.6 |  4.95 |
    #+TBLFM: $3=$2/@6$2;%.2f
    

    Profiler (python -mcProfile iter_gcd.py 4000 3000) shows that 80% of the time spent calling gcd() function, so indeed the difference is in the gcd() function.

    I wrote cython_gcd extension for Python using Cython, cython_gcd.pyx:

    def gcd(m, n):
        while n:
            n, m = m % n, n
        return m
    
    def gcd_int(int m, int n):
        while n:
            n, m = m % n, n
        return m
    

    It is used in the iter_gcd.py as follows from cython_gcd import gcd, gcd_int.

    To try the extension, run: python setup.py build_ext --inplace, where setup.py:

    from distutils.core import setup
    from distutils.extension import Extension
    from Cython.Distutils import build_ext
    
    ext_modules = [Extension("cython_gcd", ["cython_gcd.pyx"])]
    
    setup(
      name = 'Hello world app',
      cmdclass = {'build_ext': build_ext},
      ext_modules = ext_modules
    )
    

    To install the extension globally, run python setup.py install.

提交回复
热议问题