python效率提升:ctypes的初次使用

python运行效率缓慢,一直是为众人所诟病的。不过还好,python的ctypes库可以调用加载c/c++的函数库,这样python中需要效率的部分就用c/c++写,从而极大地提升python的运行效率。

下面让我们来做做测试,看看其效率的提升程度。

首先是不用ctypes的示例:
from time import time

t=time()
s=0
for i in xrange(1000):
    for j in xrange(10000):
        s += 1
print s
print time()-t

运行结果为:
10000000
4.33800005913

接着我们将循环算法那段用c++写,然后通过python调用:
from time import time
from ctypes import *

t=time()
s=0
lib = CDLL('.\ctypes\Debug\ctypes.dll')
s=lib.sum(1000,10000)
print s
print time()-t
运行结果为:
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文件即可


猜你喜欢

转载自blog.csdn.net/qq_32897527/article/details/51318559