Moich tendencyjnych eksperymentów ciąg dalszy. Zrezygnowałem z Numpy i jestem pod wrażeniem memoryviews w Cythonie. Poniższe to tak na prawdę test wydajności adresowania tablic jednowymiarowych.
Python:
import sys import random def fib(n): a, b = 0, 1 for i in range(n): a, b = b, a + b return a def showfib(n): r = [] for i in range(n): t = fib(random.randint(0,49)) r.append(t) print(t, end=" ") print() if __name__ == '__main__': n=int(sys.argv[1]) showfib(n)
Cython:
#cython: language_level=3, boundscheck=False import sys from libc.stdio cimport printf from libc.stdlib cimport rand, srand from cython.view cimport array from time import time cdef unsigned int fib(int m) nogil: cdef unsigned int a, b, i a, b = 0, 1 for i in range(m): a, b = b, a + b return a cdef showfib(n): cdef r = array(shape=(n,), itemsize=sizeof(unsigned int), format="I") cdef unsigned int [:] rv = r cdef int i cdef unsigned int t for i in range(n): t = fib(rand()%49) rv[i] = t printf("%u ", t) printf("\n") if __name__ == '__main__': n=int(sys.argv[1]) srand(int(time())) showfib(n)
Python-3.4.2:
$ time python fib.py 300000 > /dev/null
real 0m7.564s
user 0m7.543s
sys 0m0.013s
PyPy3-2.4 (portable):
$ time pypy fib.py 300000 > /dev/null
real 0m1.838s
user 0m1.813s
sys 0m0.020s
Cython-0.21.1:
$ time ./fib 300000 > /dev/null
real 0m0.189s
user 0m0.190s
sys 0m0.000s
Cython vs Python: 40,02 x szybciej.
Pypy vs Python: 4,11 x szybciej.
Cython vs PyPy: 9,72 x szybciej.