2017-06-09 87 views
-3

如何讓我的Python程序更快?這個程序計算Mandelbrot集並用龜畫出它。我認爲問題出現在for循環中。也許這些步驟花費了太多時間。如何讓我的Mandelbrot繪圖儀更快?

import numpy as np 
import turtle 
turtle.ht() 
turtle.pu() 
turtle.speed(0) 
turtle.delay(0) turtle.colormode(255) 

i= int(input("iteration = ")) 
g = int(input("accuracy = ")) 
xmin = float(input("X-min: ")) 
xmax = float(input("X-max: ")) 
ymin = float(input("Y-min: ")) 
ymax = float(input("Y-max: ")) 
cmode = int(255/i) 

input("PRESS TO START") 
for x in np.arange(xmin,xmax,1/g): 
    for y in np.arange(ymin,ymax,1/g): 
     c = x + y * 1j 
     z = 0 
     t = 1 
     for e in range(i): 
      z = z * z + c 
      if abs(z) > 3: 
       turtle.setx(g*c.real) 
       turtle.sety(g*c.imag) 
       turtle.dot(2,e*cmode,e*cmode,e*cmode) 
       t = 0 

     if t == 1: 
      turtle.setx(g*c.real) 
      turtle.sety(g*c.imag) 
      turtle.dot(2,"black") 

input("Calculated!") 
turtle.mainloop() 

Here is an example

+3

有關性能的問題更有可能在[代碼審查](https://codereview.stackexchange.com/)上得到解答。 – Badda

+0

謝謝!我是一位新用戶,非常感謝您的幫助。不知道。 @Badda – akinoioi

+0

第一次加速是在't = 0'後面添加'break'(如果繪製例程被觸發,則不需要爲此點繼續計算)。除此之外,Python並不是非常快;您可以嘗試將計算推入Numpy中,如https://thesamovar.wordpress.com/2009/03/22/fast-fractals-with-python-and-numpy/(聲稱速度提高3倍),或者您可以切換到一個像Julia https://julialang.org/這樣更快的編譯語言(甚至這個名字是合適的;-),並且它們包含mandelbrot上的20倍加速作爲他們的基準之一) –

回答

1

以下返工應該比快一百倍的原始:

import numpy as np 
import turtle 

i = int(input("iteration = ")) 
g = int(input("accuracy = ")) 
xmin = float(input("X-min: ")) 
xmax = float(input("X-max: ")) 
ymin = float(input("Y-min: ")) 
ymax = float(input("Y-max: ")) 

cmode = int(255/i) 

input("PRESS TO START") 

turtle.hideturtle() 
turtle.penup() 
turtle.speed('fastest') 
turtle.colormode(255) 
turtle.setundobuffer(None) # turn off saving undo information 

turtle.tracer(0, 0) 

for x in np.arange(xmin, xmax, 1/g): 
    for y in np.arange(ymin, ymax, 1/g): 
     c = x + y * 1j 
     z = 0 
     t = True 

     for e in range(i): 
      z = z * z + c 

      if abs(z) > 3.0: 
       turtle.setposition(g * c.real, g * c.imag) 
       rgb = e * cmode 
       turtle.dot(2, rgb, rgb, rgb) 
       t = False 
       break 

     if t: 
      turtle.setposition(g * c.real, g * c.imag) 
      turtle.dot(2, "black") 

    turtle.update() 

print("Calculated!") 

turtle.mainloop() 

的顯著的變化是使用的tracer()update()相結合,以避免視覺上繪製每點爲用戶,並繪製每個垂直列完成。

+0

另外一個重要的意義是當函數值轉義時終止迭代,當'2.0'是通常使用的值時 - 一旦函數值(幅度)超過那它永遠不會恢復。 –

+0

@WeatherVane,我計算了一個垂直條帶,'tracer()'/'update()'提高了20倍,'break'提高了約2倍。我的猜測是「tracer()」的改進是固定值,而「break」改進取決於數據,有時可能會更大。此外,'break'清除了一些令人討厭的'RuntimeWarning'關於'cdouble_scalars'的消息。 – cdlane

+0

@WeatherVane謝謝!它現在快上千倍:) – akinoioi