Skip to content

Instantly share code, notes, and snippets.

@brentp
Created October 1, 2009 00:00
Show Gist options
  • Save brentp/198576 to your computer and use it in GitHub Desktop.
Save brentp/198576 to your computer and use it in GitHub Desktop.
import array
cimport array
cdef extern from 'vec.h':
ctypedef struct vec_int "std::vector<int>":
void (* push_back)(int i)
int (* at)(int i)
vec_int new_vec_int "std::vector<int>"()
vec_int new_vec_int_length "std::vector<int>"(unsigned int length)
cdef list python_append(N):
cdef list a = []
cdef int i
for i in range(N):
a.append(i)
return a
cdef vec_int vector_append(N):
cdef vec_int v = new_vec_int()
cdef int i
for i in range(N):
v.push_back(i)
return v
cdef array.array array_append(N):
cdef int i
pyaa = array.array('i')
array.array_resize(pyaa, N)
cdef array.array aa = pyaa
for i in range(N):
aa._i[i] = i
return aa
cdef void python_get(list a, N):
cdef int i
cdef int save = 0
for i in range(N):
save = a[i]
assert save == N - 1
cdef void vector_get(vec_int a, N):
cdef int i
cdef int save = 0
for i in range(N):
save = a.at(i)
assert save == N - 1
cdef void array_get(array.array a, N):
cdef int i
cdef int save = 0
for i in range(N):
save = a._i[i]
assert save == N - 1
def main():
import time
N = 100000000
print "method: append/get"
t = time.time()
cdef list li = python_append(N)
t1 = time.time()
python_get(li, N)
print "python: %.4f / %.4f" % (t1 - t, time.time() - t1)
t = time.time()
cdef vec_int v = vector_append(N)
t1 = time.time()
vector_get(v, N)
print "vector: %.4f / %.4f" % (t1 - t, time.time() - t1)
t = time.time()
cdef array.array a = array_append(N)
t1 = time.time()
array_get(a, N)
print "array : %.4f / %.4f" % (t1 - t, time.time() - t1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment