python 中嵌入 C 语言脚本
借助 Cinpy 和 C 语言解释器 TinyCC ,可以在 python 程序里面直接嵌入 C 语言片断、不经编译直接使用 C 编写的函
数了。
win2k 平台上,简单的测试对比数据如下(递归方法计算第
四十项兔子数列fib ( 40))语言
实现
时间
(单位:秒)
评
python
官方 python 2.4.3
python fib 函数
568.718
天啊
使用 psyco 加速的 python fib 函数
17.922
比较接近,还行
使用 swig 直接转换的C 语言编写的模块
13.453
使用 Cinpy 嵌入 fib 函数
11.532
C
VC6
速度优化编译的可执行文件
5.562
TinyCC 0.9.23
编译的可执行文件
6.719
解释执行
6.813
FreeBASIC
fbc 0.16b
编译的可执行文件(-arch 486)
8.022
编译的可执行文件(-arch 686)
7.619
forth
4th 3.5a2
4th cx fib.4th
277
这个表现太失望了
4th csv fib.4th fib.hx
4th lx fib.hx
196
4th lg fib.hx fib.c
mingw -O2 fib.c -o fib.exe
110
gforth-0.6.2
Gforth-fast fib.gfth
14.719
不错,不过不是说和C 的速度可以比嘛?
怎么也就是优化的python 的速度啊
注:
其余源程序
freebasic function fib(x as integer) as integer if x<=1 then
return 1
else
return fib(x-1) + fib(x-2)
end if
end functiondim starttime, endtime as double
dim res as integerstarttime=timer
res=fib(40)
endtime=timer
print "fib(40)= ";res
print "time elapsed: "; (endtime-starttime); " s"
4th: fib ( x -- y )
dup 2 > if
dup1 - recurse
swap 2 - recurse +
exit
then
drop 1 ;time41 fib . crtime
swap -
." time elapsed " . ." s" cr
gforth-0.6.2 : fib ( x -- y )
dup 2 > if
dup1 - recurse
swap 2 - recurse +
exit
then
drop 1 ;
utime41 fib . crutime
2swap d-
." time elapsed " d. ." us" cr
如果在 windows 下使用 mingw 编译当前的TinyCC ,嵌入 C
脚本会报错:
tcc: file '/c/Program Files/tcc/libtcc1.a' not found Doug Currie 在 tcc 的邮件列表里面提供了一个补丁: Here is what I did (and reported to the mailing list) last February,
so the patch may not be accurate for more recent versions, but the
issues are the same...
I have been able to create a libtcc.dll for WinXP using MinGW/MSYS;
the changes that were necessary were very minor. Perhaps this description will help others use libtcc on Windows. First, a small bug to report:
In tcc.c the function tcc_basename() follows the line:
#if !defined(LIBTCC)
but the function tcc_basename() is used in pe_build_exports() in tccpe.c -- moving the #if line below the function tcc_basename() eliminates a link er