2017-06-09 5 views
-3

私はPythonプログラムをより速くする方法を教えてください。このプログラムはマンデルブロセットを計算し、それをカメで描画します。私は問題がforループにあると思う。たぶん、ステップに時間がかかりすぎているかもしれません。マンデルブロプロッターをもっと速くする方法は?

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/(たとえ名前が適切であっても;-)のようなよりコンパイルされた言語に変換し、それらのベンチマークの1つとして設定されたマンデルブロに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'は' cdouble_scalars'に関するいくつかの迷惑な 'RuntimeWarning'メッセージをクリーンアップします。 – cdlane

+0

@ WedeVaneありがとう! 1000倍速くなりました:) – akinoioi

関連する問題