Skip to content

Instantly share code, notes, and snippets.

@bwhite
Created July 30, 2012 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bwhite/3208889 to your computer and use it in GitHub Desktop.
Save bwhite/3208889 to your computer and use it in GitHub Desktop.
Integrating Python + C: Ctypes and Cython
import ctypes
import time
import numpy as np
import example_cython
def mult_sum(a):
b = 0
for i in range(10000):
b += a * i
return b
def mult_sum_np(a):
return np.sum(np.arange(10000) * a)
def evaluate(name, func):
st = time.time()
out = [func(x) for x in range(10)]
print('%s[%f]' % (name, time.time() - st))
return out
def main():
example = ctypes.cdll.LoadLibrary('example.so')
out = evaluate('Ctypes', example.mult_sum_c)
out2 = evaluate('Python', mult_sum)
out3 = evaluate('numpy', mult_sum_np)
out4 = evaluate('Cython', example_cython.mult_sum)
assert out == out2 == out3 == out4
if __name__ == '__main__':
main()
#include "example.h"
int mult_sum_c(int a) {
int i;
int b = 0;
for (i = 0; i < 10000; ++i) {
b += a * i;
}
return b;
}
#ifndef EXAMPLE_H
#define EXAMPLE_H
int mult_sum_c(int a);
#endif
cdef extern from "example.h":
int mult_sum_c(int)
def mult_sum(int a):
return mult_sum_c(a)
gcc -O2 --shared example.c -o example.so
cython example_cython.pyx
gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I `python -c "import distutils.sysconfig;print distutils.sysconfig.get_python_inc()"` -o example_cython.so example_cython.c example.so
LD_LIBRARY_PATH="." python demo.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment