python调用c程序

C代码

文件名 《task.c》

# include<stdio.h>

int task(int n, int p, int m){
	int i,j,k;
	unsigned long s = 0;
	for(i=0;i<n;i++){
		for(j=0;j<p;j++){
			for(k=0;k<m;k++)	{
			    s = s + i + j + k;
			}
		}
}
	return s;
}

编译 在task.c文件目录上打开命令行

gcc -o task.dll -shared -fPIC task.c
或
gcc -o task.so -shared -fPIC task.c

python 代码

from ctypes import cdll, c_long, c_int
from time import time

start = time()
dll = cdll.LoadLibrary('./task.so')
# 指定函数入参类型
dll.task.argtype = [c_int, c_int, c_int]
# 指定函数返回类型
dll.task.restype = c_long
r = dll.task(1000, 2000, 1000)
end = time()
print("c, so: time:{time},result:{r}".format(time=end - start, r=r))

start = time()
dll = cdll.LoadLibrary('./task.dll')
# 指定函数入参类型
dll.task.argtype = [c_int, c_int, c_int]
# 指定函数返回类型
dll.task.restype = c_long
r = dll.task(1000, 2000, 1000)
end = time()
print("c, dll: time:{time},result:{r}".format(time=end - start, r=r))

start = time()


def task(n, p, m):
    s = 0
    for i in range(n):
        for j in range(p):
            for k in range(m):
                s = s + i + j + k
                pass
            pass
        pass
    return s


r = task(1000, 2000, 1000)

end = time()
print("c, py: time:{time},result:{r}".format(time=end - start, r=r))

结果

c, so: time:2.56765079498291,result:3997000000000
c, dll: time:2.2216248512268066,result:3997000000000
c, py: time:113.5812668800354,result:3997000000000
posted @ 2023-05-04 17:32  hziwei  阅读(39)  评论(0编辑  收藏  举报