Compile過後的Mathematica程序大概比Python編的慢多少?
兩個分別同時用函數式編程或過程式的情況下
為什麼認為Mathematica一定比Python慢?Compile後的Mathematica程序和PyPy或者numba比還差不多。
以計算Mandelbrot set為例
Mathematica code,運行時間0.031s
mandelbrot = Compile[{x, y},
Block[{BAILOUT = 16, MAXITERATIONS = 1000,
cr = y - 0.5, ci = x, zi = 0.0, zr = 0.0, i = 0, temp, zr2, zi2},
While[True,
i++;
temp = zr zi;
zr2 = zr zr;
zi2 = zi zi;
zr = zr2 - zi2 + cr;
zi = temp + temp + ci;
If[zi2 + zr2 &> BAILOUT, Return@i];
If[i &> MAXITERATIONS, Return@0]];
0],
CompilationTarget -&> "C", RuntimeOptions -&> "Speed"
];
t1 = TimeUsed[];
write = WriteString["stdout", #] ;
Do[
Do[
write[If[mandelbrot[x/40.0, y/40.0] == 0, "*", " "]], {y, -39, 38}
];
write["
"], {x, -39, 38}
];
TimeUsed[] - t1
Python code,運行時間1.0257s
from time import time
import sys
t0=time()
def mandelbrot(x, y):
BAILOUT = 16
MAX_ITERATIONS = 1000
cr = y - 0.5
ci = x
zi = 0.0
zr = 0.0
i = 0
while True:
i += 1
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
if zi2 + zr2 &> BAILOUT:
return i
if i &> MAX_ITERATIONS:
return 0
def main():
for y in range(-39, 39):
sys.stdout.write(
)
for x in range(-39, 39):
if mandelbrot(x / 40.0, y / 40.0) == 0:
sys.stdout.write(*)
else:
sys.stdout.write( )
print()
main()
print(time()-t0)
推薦閱讀:
※計算機科學入門-門電路
※IT開發人員閑時都是怎麼消遣的?
※怎麼評價一個演算法的效率?
TAG:編程語言 | Python | 編程 | WolframMathematica | 計算機科學 |