-
-
Save ctku/3231024 to your computer and use it in GitHub Desktop.
Integrating Python + C: Ctypes and Cython
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef EXAMPLE_H | |
#define EXAMPLE_H | |
int mult_sum_c(int a); | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cdef extern from "example.h": | |
int mult_sum_c(int) | |
def mult_sum(int a): | |
return mult_sum_c(a) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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