Skip to content

Instantly share code, notes, and snippets.

@rhizoome
Last active April 14, 2018 13:33
Show Gist options
  • Save rhizoome/4efe087196dfc98d86ca8509c2533dd2 to your computer and use it in GitHub Desktop.
Save rhizoome/4efe087196dfc98d86ca8509c2533dd2 to your computer and use it in GitHub Desktop.
cython and indexing
test1: 0.08422580
test2: 0.06810107
test3: 0.04625974
test4: 0.04655976
test5: 0.00176943
test6: 0.00161580
test7: 0.00752258
test8: 0.07144928
import timeit
from test import *
num = 1000000
def test1(num):
a = [0] * num
for x in range(num):
a[x] = x
print("test1: %.8f" % timeit.timeit("t.test1(t.num)", "import __main__ as t", number=1))
print("test2: %.8f" % timeit.timeit("t.test2(t.num)", "import __main__ as t", number=1))
print("test3: %.8f" % timeit.timeit("t.test3(t.num)", "import __main__ as t", number=1))
print("test4: %.8f" % timeit.timeit("t.test4(t.num)", "import __main__ as t", number=1))
print("test5: %.8f" % timeit.timeit("t.test5(t.num)", "import __main__ as t", number=1))
print("test6: %.8f" % timeit.timeit("t.test6(t.num)", "import __main__ as t", number=1))
test7(num)
test8(num)
from libc.stdlib cimport malloc, free
cimport cython
import time
cdef class DataType:
cdef int data
def test2(num):
a = [0] * num
for x in range(num):
a[x] = x
def test3(int num):
cdef list a = [0] * num
cdef int x
for x in range(num):
a[x] = x
cpdef test4(int num):
cdef list a = [0] * num
cdef int x
for x in range(num):
a[x] = x
cpdef int test5(int num) nogil:
cdef int* m = <int*> malloc(sizeof(int) * num)
cdef int[:] a
with cython.gil:
a = <int[:num]> m
cdef int x
for x in range(num):
a[x] = x
free(m)
cpdef int test6(int num) nogil:
cdef int* m = <int*> malloc(sizeof(int) * num)
cdef int[:] a
with cython.gil:
a = <int[:num]> m
cdef int x
# Actually bounds-checks seem very efficient
with cython.boundscheck(False):
for x in range(num):
a[x] = x
free(m)
cpdef int test7(int num) except -1:
cdef list a = [0] * num
cdef DataType t
cdef int x
for x in range(num):
t = DataType()
a[x] = t
# Creating a python object is rather slow, lets assume they are pre-created
start = time.time()
for x in range(num):
t = a[x]
t.data = x
end = time.time()
print("test7: %.8f" % (end - start))
cpdef int test8(int num) except -1:
start = time.time()
cdef list a = [0] * num
cdef DataType t
cdef int x
for x in range(num):
t = DataType()
t.data = x
a[x] = t
end = time.time()
print("test8: %.8f" % (end - start))
cythonize -i test.pyx; python dotest.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment