三种实现的对比:

(1)纯python

x.py

def is_prime(num):
    for j in range(2, num):
        if (num%j)==0:
            return False
    return True




import time

a = time.time()
for i in range(10, 100000):
    is_prime(i)
b = time.time()

print(b-a)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.



(2) x2.pyx

def is_prime(num):
    for j in range(2, num):
        if (num%j)==0:
            return False
    return True




import time

a = time.time()
for i in range(10, 100000):
    is_prime(i)
b = time.time()

print(b-a)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.


编译文件:

x2_setup.py

from distutils.core import setup
from Cython.Build import cythonize

setup(
  name = 'Great Circle module v1',
  ext_modules = cythonize("x2.pyx", 
                          #compiler_directives={'language_level' : "3"}
                          # or "2" or "3str"
                          ),
)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

编译:

python x2_setup.py build_ext --inplace



(3) x3.pyx

def is_prime(num):
    cdef int j
    for j in range(2, num):
        if (num%j)==0:
            return False
    return True




import time

a = time.time()
for i in range(10, 100000):
    is_prime(i)
b = time.time()

print(b-a)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.


编译文件:

x3_setup.py

from distutils.core import setup
from Cython.Build import cythonize

setup(
  name = 'Great Circle module v1',
  ext_modules = cythonize("x3.pyx", 
                          #compiler_directives={'language_level' : "3"}
                          # or "2" or "3str"
                          ),
)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

编译:

python x3_setup.py build_ext --inplace



运行效果对比:

python高性能计算:cython入门代码_Cython