python调用C程序

2022-12-08 07:56:50

python编程方便,C运行效率高
在写python程序中如果需要提效的逻辑单元可以通过C语言实现

python调用C++程序.

一.C语言测试逻辑

step1: gcc环境

step2: 代码文件tmp.c

#include <stdio.h>

/*
char	1 字节	-128 到 127 或 0 到 255
unsigned char	1 字节	0 到 255
signed char	1 字节	-128 到 127
int	2 或 4 字节	-32,768 到 32,767 或 -2,147,483,648 到 2,147,483,647
unsigned int	2 或 4 字节	0 到 65,535 或 0 到 4,294,967,295
short	2 字节	-32,768 到 32,767
unsigned short	2 字节	0 到 65,535
long	4 字节	-2,147,483,648 到 2,147,483,647
unsigned long	4 字节	0 到 4,294,967,295

*/

// 为了测试C程序返回数据后观察内存溢出
long return_c_num(long num){
    printf("c num=%ld \n", num);
    return num;
}

// 加法测试运行效率
long long add_c(long d){
    printf("d=%ld \n", d);
    long long sum = 0;
    for (; d; d--){
        sum += d;
    }
    printf("sum=%lld \n", sum);
    return sum;

long long ppow(long b) {
    long long r = 1;
    for (; b; b--) {
        r *= 2;
    }
    return r;
}

int main() {
   
    long long sum;
    sum = add_c(10000);
    printf("sum=%lld \n", sum);
    
    long long pow;
    pow = ppow(20);
    printf("pow=%lld \n", pow);
    
    return 0;
}
}

step3:

gcc tmp.c -shared -o ./tmp.so

生成文件tmp.so

二.python调用测试

code: python_use_c.py

from ctypes import cdll
import time

tmp_c = cdll.LoadLibrary("./tmp.so")

def add_circle_test_c(num):
    start_time = time.time()
    tmp_c.add_c(num)
    end_time = time.time()
    print(f'cost {end_time-start_time} ms')


def add_circle_test_python3(num):
    print(f'd={num}')
    start_time = time.time()
    sum = 0
    for i in range(num+1):
        sum += i
    print(f'sum={sum}')
    end_time = time.time()
    print(f'cost {end_time-start_time} ms')


def get_c_num(num):
    return_result = tmp_c.return_c_num(num)
    print(f"python num={return_result}")
    
if __name__ == '__main__':
    num = 10000000
    print('### test c ###')
    add_circle_test_c(num)
    print('### test python ###')
    add_circle_test_python3(num)

    print('\n')
    print('测试内存溢出')
    num =  2147483647
    print(f'origin num: {num}')
    get_c_num(num)
    num = 2147483648
    print(f'origin num: {num}')
    get_c_num(num)

运行结果分析:

### test c ###
d=10000000 
sum=50000005000000 
cost 0.02991008758544922 ms
### test python ###
d=10000000
sum=50000005000000
cost 0.5426278114318848 ms


测试内存溢出
origin num: 2147483647
c num=2147483647 
python num=2147483647
origin num: 2147483648
c num=-2147483648 
python num=-2147483648

时效

1000W次叠加,python耗时0.54s,C耗时0.03s,C提效显著

内存溢出(注意点)

超过一个限度:
i n t 4 字 节 − 2 , 147 , 483 , 648 到 2 , 147 , 483 , 647 int 4 字节 -2,147,483,648 到 2,147,483,647 int42,147,483,6482,147,483,647
python只用4个字节存储,则python接受的数据会有问题

  • 作者:董蝈蝈
  • 原文链接:https://blog.csdn.net/weixin_41566471/article/details/124075987
    更新时间:2022-12-08 07:56:50