Python调用C模块以及性能分析

简介:

Python调用C模块以及性能分析


一.c,ctypes和python的数据类型的对应关系

  • ctypes type ctype Python type
  • c_char char 1-character string
  • c_wchar wchar_t 1-character unicode string
  • c_byte char int/long
  • c_ubyte unsigned char int/long
  • c_short short int/long
  • c_ushort unsigned short int/long
  • c_int int int/long
  • c_uint unsigned int int/long
  • c_long long int/long
  • c_ulong unsigned long int/long
  • c_longlong __int64 or long long int/long
  • c_ulonglong unsigned __int64 or unsigned long long int/long
  • c_float float float
  • c_double double float
  • c_char_p char * (NUL terminated) string or None
  • c_wchar_p wchar_t * (NUL terminated) unicode or None
  • c_void_p void * int/long or None

2.操作int

 
  1. >>> from ctypes import * 
  2.  
  3. >>> c=c_int(34) 
  4.  
  5. >>> c 
  6.  
  7. c_int(34) 
  8.  
  9. >>> c.value 
  10.  
  11. 34 
  12.  
  13. >>> c.value=343 
  14.  
  15. >>> c.value 
  16.  
  17. 343  

3.操作字符串

 
  1. >>> p=create_string_buffer(10) 
  2.  
  3. >>> p.raw 
  4.  
  5. '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 
  6.  
  7. >>> p.value='fefefe' 
  8.  
  9. >>> p.raw 
  10.  
  11. 'fefefe\x00\x00\x00\x00' 
  12.  
  13. >>> p.value='fefeeeeeeeeeeeeeeeeeeeeeee'  #字符串太长,报错 
  14.  
  15. Traceback (most recent call last): 
  16.  
  17.   File "<stdin>", line 1, in <module> 
  18.  
  19. ValueError: string too long  

4.操作指针

 
  1. >>> i=c_int(999) 
  2.  
  3. >>> pi=pointer(i) 
  4.  
  5. >>> pi 
  6.  
  7. <__main__.LP_c_int object at 0x7f7be1983b00> 
  8.  
  9. >>> pi.value 
  10.  
  11. Traceback (most recent call last): 
  12.  
  13.   File "<stdin>", line 1, in <module> 
  14.  
  15. AttributeError: 'LP_c_int' object has no attribute 'value' 
  16.  
  17. >>> pi.contents 
  18.  
  19. c_int(999) 
  20.  
  21. >>> pi.contents=c_long(34343) 
  22.  
  23. >>> pi.contents 
  24.  
  25. c_int(34343)  
  • 通过pointer获取一个值的指针
  • 通过contents获取一个指针的值

5.c的结构体

 
  1. #定义一个c的structure,包含两个成员变量x和y 
  2.  
  3. >>> class POINT(Structure): 
  4.  
  5. ...     _fields_=[('x',c_int),('y',c_int)] 
  6.  
  7. ... 
  8.  
  9. >>> point=POINT(2,4) 
  10.  
  11. >>> point 
  12.  
  13. <__main__.POINT object at 0x7f7be1983b90> 
  14.  
  15. >>> point.x,point.y 
  16.  
  17. (2, 4) 
  18.  
  19. >>> porint=POINT(y=2) 
  20.  
  21. >>> porint 
  22.  
  23. <__main__.POINT object at 0x7f7be1983cb0> 
  24.  
  25. >>> point=POINT(y=2) 
  26.  
  27. >>> point.x,point.y 
  28.  
  29. (0, 2) 
  30.  
  31. 定义一个类型为POINT的数组 
  32.  
  33. >>> POINT_ARRAY=POINT*3 
  34.  
  35. >>> pa=POINT_ARRAY(POINT(2,3),POINT(2,4),POINT(2,5)) 
  36.  
  37. >>> for i in pa:print pa.y 
  38.  
  39. ... 
  40.  
  41. Traceback (most recent call last): 
  42.  
  43.   File "<stdin>", line 1, in <module> 
  44.  
  45. AttributeError: 'POINT_Array_3' object has no attribute 'y' 
  46.  
  47. >>> for i in pa:print i.y 
  48.  
  49. ... 
  50.  
  51.  
  52.  
  53. 5  

6.访问so文件

1.创建一个c文件

 
  1. #include <stdio.h> 
  2.  
  3. int hello_world(){ 
  4.  
  5.     printf("Hello World\n"); 
  6.  
  7.     return 0; 
  8.  
  9.  
  10. int main(){ 
  11.  
  12.         hello_world(); 
  13.  
  14.         return 0; 
  15.  
  16. }  

2.编译成动态链接库

 
  1. gcc hello_world.c  -fPIC -shared -o hello_world.so 

3.python中调用库中的函数

 
  1. from ctypes import cdll 
  2.  
  3. c_lib=cdll.LoadLibrary('./hello_world.so'
  4.  
  5. c_lib.hello_world()  

二.测试c的性能和python的差别

sum.c

 
  1. int sum(int num){ 
  2.  
  3.     long sum=0; 
  4.  
  5.     int i =0; 
  6.  
  7.     for( i=1;i<=num;i++){ 
  8.  
  9.         sum=sum+i; 
  10.  
  11.     }; 
  12.  
  13.     return sum
  14.  
  15.  
  16. int main(){ 
  17.  
  18.     printf("%d",sum(10)); 
  19.  
  20.     return 0; 
  21.  
  22. }  
  • 测试方案:计算1-100的和
  • 测试次数:100万次

1. 直接用c来执行,通linux 的time命令来记录执行的用时

sum.c:

 
  1. #include <stdio.h> 
  2.  
  3. int sum(int num){ 
  4.  
  5.     long sum=0; 
  6.  
  7.     int i =0; 
  8.  
  9.     for( i=1;i<=num;i++){ 
  10.  
  11.         sum=sum+i; 
  12.  
  13.     }; 
  14.  
  15.     return sum
  16.  
  17.  
  18. int main(){ 
  19.  
  20.     int i ; 
  21.  
  22.     for (i=0;i<1000000;i++){ 
  23.  
  24.     sum(100); 
  25.  
  26.     } 
  27.  
  28.     return 0; 
  29.  
  30. }  

测试结果的例子:

  • real 1.16
  • user 1.13
  • sys 0.01

2.通过Python调用so文件和python的测试结果

sum_test.py:

 
  1. def sum_python(num): 
  2.  
  3.     s = 0 
  4.  
  5.     for i in xrange(1,num+1): 
  6.  
  7.         s += i 
  8.  
  9.     return s 
  10.  
  11.   
  12.  
  13.   
  14.  
  15. from ctypes import cdll 
  16.  
  17.   
  18.  
  19. c_lib = cdll.LoadLibrary('./sum.so'
  20.  
  21.   
  22.  
  23.   
  24.  
  25. def sum_c(num): 
  26.  
  27.     return c_lib.sum(num) 
  28.  
  29.   
  30.  
  31.   
  32.  
  33. def test(num): 
  34.  
  35.     import timeit 
  36.  
  37.   
  38.  
  39.     t1 = timeit.Timer('c_lib.sum(%d)' % num, 'from __main__ import c_lib'
  40.  
  41.     t2 = timeit.Timer('sum_python(%d)' % num, 'from __main__ import sum_python'
  42.  
  43.     print 'c', t1.timeit(number=1000000) 
  44.  
  45.     print 'python', t2.timeit(number=1000000) 
  46.  
  47.   
  48.  
  49.   
  50.  
  51. if __name__ == '__main__'
  52.  
  53.     test(100)  

测试结果的例子

 
  1. c 1.02756714821 
  2.  
  3. python 7.90672802925  

3.测试erlang的测试结果

刚刚学了erlang,那就一起测试一下erlang的运算性能

sum.erl:

 
  1. -module(sum). 
  2.  
  3. -export([sum/2,sum_test/2]). 
  4.  
  5. sum(0,Sum) -> 
  6.  
  7.         Sum
  8.  
  9. sum(Num,Sum) -> 
  10.  
  11.         sum(Num-1,Sum+Num). 
  12.  
  13. sum_test(Num,0) -> 
  14.  
  15.         0; 
  16.  
  17. sum_test(Num,Times) -> 
  18.  
  19.         sum(Num,0), 
  20.  
  21.         sum_test(Num,Times-1).  

调用:

 
  1. timer:tc(sum,sum_test,[100,1000000]). 

测试结果的例子:

 
  1. {2418486,0} 

4.测试结果

用上面的测试方法,进行10次测试,去除最大值和最小值,再计算平均值,得出:

单位:秒

  • 求和的运行,使用的内存比较小,但是占用CPU资源比较多。
  • 原生的C是最快的,Python调用c会稍微慢一点,原因是计算100的和的操作是在c里面做的,而执行100万次的逻辑是在python做的
  • erlang的性能虽然比c稍慢,但是也是不错的,
  • Python的运行效率惨不忍睹。。。 
作者:佚名
来源:51CTO
相关文章
|
17天前
|
存储 开发者 Python
Python中的collections模块与UserDict:用户自定义字典详解
【4月更文挑战第2天】在Python中,`collections.UserDict`是用于创建自定义字典行为的基类,它提供了一个可扩展的接口。通过继承`UserDict`,可以轻松添加或修改字典功能,如在`__init__`和`__setitem__`等方法中插入自定义逻辑。使用`UserDict`有助于保持代码可读性和可维护性,而不是直接继承内置的`dict`。例如,可以创建一个`LoggingDict`类,在设置键值对时记录操作。这样,开发者可以根据具体需求定制字典行为,同时保持对字典内部管理的抽象。
|
18天前
|
存储 缓存 算法
Python中collections模块的deque双端队列:深入解析与应用
在Python的`collections`模块中,`deque`(双端队列)是一个线程安全、快速添加和删除元素的双端队列数据类型。它支持从队列的两端添加和弹出元素,提供了比列表更高的效率,特别是在处理大型数据集时。本文将详细解析`deque`的原理、使用方法以及它在各种场景中的应用。
|
3天前
|
Python
python学习14-模块与包
python学习14-模块与包
|
5天前
|
SQL 关系型数据库 数据库
Python中SQLite数据库操作详解:利用sqlite3模块
【4月更文挑战第13天】在Python编程中,SQLite数据库是一个轻量级的关系型数据库管理系统,它包含在一个单一的文件内,不需要一个单独的服务器进程或操作系统级别的配置。由于其简单易用和高效性,SQLite经常作为应用程序的本地数据库解决方案。Python的内置sqlite3模块提供了与SQLite数据库交互的接口,使得在Python中操作SQLite数据库变得非常容易。
|
10天前
|
索引 Python
「Python系列」Python operator模块、math模块
Python的`operator`模块提供了一系列内置的操作符函数,这些函数对应于Python语言中的内建操作符。使用`operator`模块可以使代码更加清晰和易读,同时也能提高性能,因为它通常比使用Python内建操作符更快。
27 0
|
14天前
|
数据采集 网络协议 API
python中其他网络相关的模块和库简介
【4月更文挑战第4天】Python网络编程有多个流行模块和库,如requests提供简洁的HTTP客户端API,支持多种HTTP方法和自动处理复杂功能;Scrapy是高效的网络爬虫框架,适用于数据挖掘和自动化测试;aiohttp基于asyncio的异步HTTP库,用于构建高性能Web应用;Twisted是事件驱动的网络引擎,支持多种协议和异步编程;Flask和Django分别是轻量级和全栈Web框架,方便构建不同规模的Web应用。这些工具使网络编程更简单和高效。
|
18天前
|
数据采集 数据挖掘 Python
Python中collections模块的Counter计数器:深入解析与应用
在Python的`collections`模块中,`Counter`是一个强大且实用的工具,它主要用于计数可哈希对象。无论是统计单词出现的频率,还是分析数据集中元素的分布情况,`Counter`都能提供快速且直观的结果。本文将深入解析`Counter`计数器的原理、用法以及它在实际应用中的价值。
|
19天前
|
Python
Python中的math和cmath模块:数学运算的得力助手
Python作为一种功能强大的编程语言,提供了丰富的数学运算功能。其中,math和cmath模块就是Python中用于数学运算的重要工具。math模块提供了基本的数学函数和常量,适用于实数运算;而cmath模块则提供了对复数运算的支持,使得Python在数学计算和工程应用中更加灵活和强大。
|
22天前
|
数据挖掘 Python
Python中的datetime模块:轻松拿捏时间操作
Python的`datetime`模块是处理日期和时间的核心工具,包括`date`、`time`、`datetime`、`timedelta`类。它可以创建、操作和格式化日期时间。
19 2
|
24天前
|
Python
Python random模块(获取随机数)常用方法和使用例子
`random`模块在Python中用于生成随机数。
20 0

热门文章

最新文章