unformat14n
unformat14n
MModular
Created by unformat14n on 6/8/2024 in #questions
Mandelbrot example equivalent python code
I was reading and following the code in the blog post https://www.modular.com/blog/how-mojo-gets-a-35-000x-speedup-over-python-part-1. I was trying to run the snippets provided but they don't compile by themselves because they are not complete. I found the source code in github https://github.com/modularml/mojo/blob/main/examples/mandelbrot.mojo. I ran this and it works with these results on my machine: Number of physical cores: 8 Vectorized: 14.634963190184047 ms Parallelized: 4.1496295025728989 ms Parallel speedup: 3.5268120156534257 I am trying to write the most basic python code to compare. I wrote this:
MAX_ITERS = 1000

def mandelbrot_kernel(c):
z = c
nv = 0
for i in range(MAX_ITERS):
if abs(z) > 2:
break
z = z*z + c
nv += 1
return nv

height = 4096
width = 4096
min_x = -2.0
max_x = 0.47
min_y = -1.12
max_y = 1.12
scalex = (max_x - min_x) / width
scaley = (max_y - min_y) / height

output = [[0 for x in range(width)] for y in range(height)]

for h in range(height):
cy = min_y + h * scaley
for w in range(width):
cx = min_x + w * scalex
output[w][h] = mandelbrot_kernel(complex(cx, cy))
MAX_ITERS = 1000

def mandelbrot_kernel(c):
z = c
nv = 0
for i in range(MAX_ITERS):
if abs(z) > 2:
break
z = z*z + c
nv += 1
return nv

height = 4096
width = 4096
min_x = -2.0
max_x = 0.47
min_y = -1.12
max_y = 1.12
scalex = (max_x - min_x) / width
scaley = (max_y - min_y) / height

output = [[0 for x in range(width)] for y in range(height)]

for h in range(height):
cy = min_y + h * scaley
for w in range(width):
cx = min_x + w * scalex
output[w][h] = mandelbrot_kernel(complex(cx, cy))
But that python code takes 7 minutes to run. This is 30285x slower than the vectorized code. Am I doing this right? The page only claimed an 89x but maybe the blog post has not yet been written to explain the vectorized code speed up?
4 replies