Ive written a function which uses turtle to draw a Mandelbrot set, however its very slow (~10's minutes) for any decent resolution, how could I make my code more efficient?
import math, turtle
screen = turtle.Screen()
screen.setup(width=1000, height=600 ,startx=0, starty=0)
screen.bgcolor('black')
screen.tracer(0)
pen = turtle.Turtle()
pen.penup()
pen.speed(10)
width = 800
height = 600
MAX_ITER=80
def draw_mandelbrot(c):
z = 0
n = 0
while abs(z) <= 2 and n < MAX_ITER:
z = z * z + c
n += 1
return n
def generate_mandelbrot_set(StartR, StartI, EndR, EndI):
screen.setworldcoordinates(StartR, StartI, EndR, EndI)
screen.bgcolor("black")
for x in range(width):
for y in range(height):
c = complex(StartR + (x / width) * (EndR - StartR), StartI + (y / height) * (EndI - StartI))
m = draw_mandelbrot(c)
color = (255 - int(m * 255 / MAX_ITER)) / 255
pen.goto(StartR + (x / width) * (EndR - StartR), StartI + (y / height) * (EndI - StartI))
if y == 0:
pen.pendown()
elif y == height-1 :
pen.penup()
pen.color(color, color, color)
pen.dot()
generate_mandelbrot_set(-2,-1,1,1)
screen.update()
screen.mainloop()
Im new to coding so any advice would be hugely appreciated!

I tried your code with a 80x60 resolution and I really liked the look of the little vertical lines and dots. Doing the Mandelbrot set in turtle graphics is impressive! You could speed it up by using
screen.tracer(0, 0)andpen.speed('fastest')(which is faster than 10) for some minimal gains.But at 800x600, the turtle is the wrong tool for the job: not only the artistic lines won't be visible, Python will spend a lot of time doing cute things like animating the turtle movements (which is only disabled at speed 11).
My suggestion would be to ditch the turtle and use a graphical interface with a canvas object, where you can place individual pixels. Python comes with Tkinter, a simple but efficient library that can do this.
Here's the exact same rendering logic, translated to Tkinter, finishing in under 7 seconds: