前文我们已经说过了如何用freebasic编制dll被python调用,本节是通过示例来对比其运行效率。
废话不说,上代码:
myfib.bas
编译后生成myfib.dll
fbc -s gui -dll -export "myfib.bas"
'mylib.bas
function fib Cdecl Alias "fib"( x as integer) as Integer Export
if x<=1 then
return 1
else
return fib(x-1) + fib(x-2)
end if
end function
编译.dll,命名为myfib.dll,拷贝到python.exe 目录下
2. python 代码:
# -*- coding: cp936 -*-
from ctypes import *
lib=CDLL("myfib.dll")
# Fibonacci in Python
def fibpy(x):
if x<=1: return 1
return fibpy(x-1)+fibpy(x-2)
# test fibpy(x)
def sspy(x):
import time
t0=time.time()
fibpy(x)
t1=time.time()
print "Python coast time:",(t1-t0)
# test dll of freebasic: fib(40)
def ssfb(x):
import time
t0=time.time()
lib.fib(x)
t1=time.time()
print "coast time:",(t1-t0)
print "1.================="
print "test for python function fibpy(40)"
sspy(40)
print ""
print "2.================="
print "test for dll of freebasic fib(40)"
ssfb(40)
i=raw_input("input anything for Exit")
生成的结果大家都关心的哈,如下:
对比一下,提高26倍哦。
转帖请注明出处。
来源:oschina
链接:https://my.oschina.net/u/577912/blog/223010