摘要:利用 gcc -o libpycall.so -shared -fPIC filename.c 将 C/C++文件编译成.so文件,供 python 调用
/*gcc -o libpycall.so -shared -fPIC pycall.c */
#include <stdio.h>
#include <stdlib.h>
int fact(int n)
{
if (n <= 1)
return 1;
else
return n*fact(n-1);
}
import ctypes
import time
def fact(n): #function write in python to compare
if n<=1:return 1
else:return n*fact(n-1)
if __name__=='__main__':
now=time.time()
for i in range(10000):
n=fact(100)
end=time.time()
print 'the python fact takes:',end-now
ll = ctypes.cdll.LoadLibrary #call c/c++ function
lib = ll("./libpycall.so")
for i in range(10000):
n=lib.fact(100)
print 'the c fact taks:',time.time()-end