python效率提升:ctypes的初次使用
来源:互联网 发布:网站美工制作 编辑:程序博客网 时间:2024/05/18 13:31
python运行效率缓慢,一直是为众人所诟病的。不过还好,python的ctypes库可以调用加载c/c++的函数库,这样python中需要效率的部分就用c/c++写,从而极大地提升python的运行效率。
下面让我们来做做测试,看看其效率的提升程度。
首先是不用ctypes的示例:
from time import timet=time()s=0for i in xrange(1000): for j in xrange(10000): s += 1print sprint time()-t
运行结果为:
10000000
4.33800005913
接着我们将循环算法那段用c++写,然后通过python调用:
from time import timefrom ctypes import *t=time()s=0lib = CDLL('.\ctypes\Debug\ctypes.dll')s=lib.sum(1000,10000)print sprint time()-t
运行结果为:
10000000
0.118000030518
10000000
0.118000030518
可以看到第一个程序运行了4秒以上,而第二个只需0.1秒,运行效率得到了极大地提升。
来讲讲ctypes,ctypes两种加载方式:
>>> from ctypes import *>>> libc = cdll . LoadLibrary ( "libc.so.6" )>>> libc.printf("%d",2)>>> from ctypes import *>>> libc = CDLL ( "libc.so.6" )>>> libc.printf("%d",2)我是win7系统,亲测这两种方式可用。另外有些人windows系统用windll方式加载,其实是不可以的。
最后讲讲我的dll文件
我用的VC++ 6.0,新建Win32 Dynamic-Link Libraby工程,命名为ctypes;再新建C/C++ Header File与C++ Source File,分别命名为ctypes.h、ctypes.cpp
ctypes.h
#ifndef _MYDLL_H_#define _MYDLL_H_extern "C" _declspec (dllexport) int sum(int a,int b); //添加.cpp中的定义的函数 #endif
ctypes.cpp
#include "ctypes.h" //.h 的名字#include <stdio.h>int sum(int a,int b){int s,i,j;s = 0;for(i=0;i<a;i++){for(j=0;j<b;j++){s += 1;}}return s;}
最后组建dll文件即可
0 0
- python效率提升:ctypes的初次使用
- Python的学习(三十二)---- ctypes库的使用整理
- ctypes: 使用python调用C编写的动态链接库
- Python调用windows下DLL详解 - ctypes库的使用
- Python调用windows下DLL详解 - ctypes库的使用
- Python调用windows下DLL详解 - ctypes库的使用
- Python调用windows下DLL详解 - ctypes库的使用
- Python调用windows下DLL详解 - ctypes库的使用
- Python调用windows下DLL详解 - ctypes库的使用
- Python调用windows下DLL详解 - ctypes库的使用
- Python调用windows下DLL详解 - ctypes库的使用
- Python调用windows下DLL详解 - ctypes库的使用
- Python调用windows下DLL详解 - ctypes库的使用
- python使用 C语言类型、ctypes 的用法
- 神奇的Python ctypes模块
- Python的点点滴滴(ctypes)
- ListView的使用用ViewHolder提升效率
- 如何提升 TortoiseSVN 的使用效率
- Java基础之分支结构和循环
- Andriod mutidex相关的文章
- 【BZOJ4534】基础排序算法练习题
- eclipse关联源码
- 序列模式挖掘
- python效率提升:ctypes的初次使用
- Leetcode - Contains Duplicate
- Linux设备模型(8)_platform设备
- 在Navicat中修改表结构
- 无参和有参构造方法
- poll设备方法
- [JavaScript]'this'详解
- Spark生态之Alluxio学习1---单机版搭建和运行
- struct和 union用 sizeof 看字节对齐