Skip to content

Project: Mandelbrot Set

The Mandelbrot set is a famous picture made from a tiny formula. It’s also the classic test for “how fast is this language at number crunching?”, because it’s nothing but multiplications and additions in a loop, millions of times. In this project you’ll draw it in the terminal with plain Mojo, measure how long a big version takes, and then rewrite the inner loop with SIMD so it works on several points at once.

You’ll practise functions, while and for loops, constants, numbers, SIMD and benchmarking. No complex-number library needed: we’ll do the math with two plain Float64s.

This, printed by a 30-line Mojo program:

..........................................................
.............................:::::::-+-:::::::.............
..........................:::::::::::--=#+#+-::::::..........
........................:::::::::::::-=+*###==-::::::::.......
.......................:::::::::::-----=##@@@@#+---::::::::.....
.....................::::::::::-#+%+==%+**#@@@@#*++#=---=%-::....
..................:::::::::::---==#@@#@@@@@@@@@@@@@@@@%#@@#=:::...
..............::::::::::::----=###@@@@@@@@@@@@@@@@@@@@@@#+=--:::..
.......:::::::::-=+==-=++=---==*##@@@@@@@@@@@@@@@@@@@@@@@@@@%+-:::.
..:::::::::::::--==*#@##@#@#*+*#@@@@@@@@@@@@@@@@@@@@@@@@@@@#+--::::
.::::::::::::--===+#@@@@@@@@@@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@##-:::::
:::---=----==++*#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#=--:::::

That’s the top half; the bottom half is its mirror image. Then we’ll make the same computation run about four times faster on our test machine.

Every point on the picture is a pair of numbers (cx, cy). For each point, start with x = 0, y = 0 and repeat this step:

new x = x*x - y*y + cx
new y = 2*x*y + cy

If the point (x, y) ever gets further than 2 away from the center (that is, x*x + y*y > 4), it will fly off to infinity, and the point (cx, cy) is outside the set. If it stays close for as many steps as we’re willing to try, we say it’s inside. The number of steps before it escapes is what we’ll turn into a character later.

(If you know complex numbers: this is z = z*z + c with z = x + iy. You don’t need to know that to follow along.)

def escape_time(cx: Float64, cy: Float64, max_iter: Int) -> Int:
var x: Float64 = 0
var y: Float64 = 0
for i in range(max_iter):
if x * x + y * y > 4:
return i
var new_x = x * x - y * y + cx
y = 2 * x * y + cy
x = new_x
return max_iter
def main():
print("(0, 0): ", escape_time(0, 0, 100))
print("(-1, 0): ", escape_time(-1, 0, 100))
print("(1, 0): ", escape_time(1, 0, 100))
print("(0.3, 0.5): ", escape_time(0.3, 0.5, 100))
print("(-0.75, 0.1):", escape_time(-0.75, 0.1, 100))

Output:

(0, 0): 100
(-1, 0): 100
(1, 0): 3
(0.3, 0.5): 100
(-0.75, 0.1): 33

(0, 0), (-1, 0) and (0.3, 0.5) never escape, so they get the full 100: they’re inside. (1, 0) escapes after 3 steps (x goes 0, 1, 2, 5…). (-0.75, 0.1) is close to the edge of the set: it hangs around for 33 steps before escaping. Points like that are where all the detail in the picture comes from.

Two small things in the code:

  • new_x holds the new x for a moment, because the formula for y still needs the old x. Updating x first is the classic bug here.
  • var x: Float64 = 0 says the type out loud. Without it, var x = 0 would make an Int, and x * x - y * y + cx would mix an Int with a Float64, which Mojo won’t do on its own.

Now we walk over a grid of 72 columns and 24 rows, turn each character position into a point (cx, cy), and pick a character by how fast the point escaped. Points inside the set get @:

comptime WIDTH = 72
comptime HEIGHT = 24
comptime MAX_ITER = 100
comptime SHADES = " .:-=+*%#"
def escape_time(cx: Float64, cy: Float64, max_iter: Int) -> Int:
var x: Float64 = 0
var y: Float64 = 0
for i in range(max_iter):
if x * x + y * y > 4:
return i
var new_x = x * x - y * y + cx
y = 2 * x * y + cy
x = new_x
return max_iter
def main():
var step = 2.8 / Float64(WIDTH - 1)
for row in range(HEIGHT):
var cy = -1.2 + 2.4 * Float64(row) / Float64(HEIGHT - 1)
var line = String()
for col in range(WIDTH):
var cx = -2.15 + Float64(col) * step
var n = escape_time(cx, cy, MAX_ITER)
if n == MAX_ITER:
line += "@"
else:
line += SHADES[byte=min(n // 2, 8)]
print(line.rstrip())

Output:

..........................................................
.............................:::::::-+-:::::::.............
..........................:::::::::::--=#+#+-::::::..........
........................:::::::::::::-=+*###==-::::::::.......
.......................:::::::::::-----=##@@@@#+---::::::::.....
.....................::::::::::-#+%+==%+**#@@@@#*++#=---=%-::....
..................:::::::::::---==#@@#@@@@@@@@@@@@@@@@%#@@#=:::...
..............::::::::::::----=###@@@@@@@@@@@@@@@@@@@@@@#+=--:::..
.......:::::::::-=+==-=++=---==*##@@@@@@@@@@@@@@@@@@@@@@@@@@%+-:::.
..:::::::::::::--==*#@##@#@#*+*#@@@@@@@@@@@@@@@@@@@@@@@@@@@#+--::::
.::::::::::::--===+#@@@@@@@@@@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@##-:::::
:::---=----==++*#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#=--:::::
:::---=----==++*#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#=--:::::
.::::::::::::--===+#@@@@@@@@@@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@##-:::::
..:::::::::::::--==*#@##@#@#*+*#@@@@@@@@@@@@@@@@@@@@@@@@@@@#+--::::
.......:::::::::-=+==-=++=---==*##@@@@@@@@@@@@@@@@@@@@@@@@@@%+-:::.
..............::::::::::::----=###@@@@@@@@@@@@@@@@@@@@@@#+=--:::..
..................:::::::::::---==#@@#@@@@@@@@@@@@@@@@%#@@#=:::...
.....................::::::::::-#+%+==%+**#@@@@#*++#=---=%-::....
.......................:::::::::::-----=##@@@@#+---::::::::.....
........................:::::::::::::-=+*###==-::::::::.......
..........................:::::::::::--=#+#+-::::::..........
.............................:::::::-+-:::::::.............
..........................................................

How the grid works:

  • cx goes from -2.15 to 0.65 across the 72 columns, in steps of 2.8 / 71. cy goes from -1.2 to 1.2 down the 24 rows. That window is where the interesting part of the set lives.
  • SHADES[byte=...] picks one character from the string by its byte position. min(n // 2, 8) turns the escape count into a position from 0 to 8: points that escape at once get a space, slower ones get denser characters.
  • line.rstrip() removes the spaces at the end of each line, so nothing invisible is left behind.

Terminal characters are about twice as tall as they are wide, which is why the window is 2.8 wide but only 2.4 tall, with three times as many columns as rows. Change WIDTH and HEIGHT to fit your terminal.

An ASCII picture has only 1,728 points, which is too small to time. For a real test, let’s compute a 1600 by 1200 grid with up to 200 steps per point, and just count how many points are inside. Timing uses perf_counter_ns() from std.time, like in Mojo Benchmarking:

from std.time import perf_counter_ns
comptime MAX_ITER = 200
def escape_time(cx: Float64, cy: Float64, max_iter: Int) -> Int:
var x: Float64 = 0
var y: Float64 = 0
for i in range(max_iter):
if x * x + y * y > 4:
return i
var new_x = x * x - y * y + cx
y = 2 * x * y + cy
x = new_x
return max_iter
def count_plain(width: Int, height: Int) -> Int:
var inside = 0
var step = 2.8 / Float64(width - 1)
for row in range(height):
var cy = -1.2 + 2.4 * Float64(row) / Float64(height - 1)
for col in range(width):
var cx = -2.15 + Float64(col) * step
if escape_time(cx, cy, MAX_ITER) == MAX_ITER:
inside += 1
return inside
def main():
var start = perf_counter_ns()
var inside = count_plain(1600, 1200)
var ms = (perf_counter_ns() - start) // 1_000_000
print("plain:", inside, "points inside,", ms, "ms")

You’ll see something like this (on our test machine, a 4-core Linux VM with an Intel Xeon at 2.1 GHz; your numbers will be different):

plain: 435444 points inside, 242 ms

That’s about 1.9 million points, and many of them run all 200 steps. We print the count on purpose: it proves the work was really done (a compiler is allowed to skip work whose result nobody uses), and it gives us something to check the faster version against.

Your CPU can do the same math on several numbers in one instruction. That’s SIMD, and Mojo gives you direct access to it with the SIMD[dtype, width] type: a small vector of numbers where +, - and * work on every lane at once. The Mojo SIMD lesson explains the basics, and the SIMD reference lists every method.

The plan: instead of one cx, take W neighbouring points of a row and run the formula on all of them together. The tricky part is that points escape at different times. A plain if ... return can’t work, because it would stop all lanes at once. So each lane keeps its own count, and we use a mask to know which lanes are still inside:

from std.math import iota
from std.sys import simd_width_of
comptime W = simd_width_of[DType.float64]()
def escape_time_simd(
cx: SIMD[DType.float64, W], cy: Float64, max_iter: Int
) -> SIMD[DType.int64, W]:
var x = SIMD[DType.float64, W](0)
var y = SIMD[DType.float64, W](0)
var counts = SIMD[DType.int64, W](0)
for _ in range(max_iter):
var still_inside = (x * x + y * y).le(4)
if not still_inside.reduce_or():
break
counts += still_inside.cast[DType.int64]()
var new_x = x * x - y * y + cx
y = 2 * x * y + cy
x = new_x
return counts
def main():
print("lanes:", W)
var cx = iota[DType.float64, W](0) * 0.25 - 1.0
print("cx: ", cx)
print("steps:", escape_time_simd(cx, 0.0, 100))

You’ll see something like this (on our test machine, where W is 8):

lanes: 8
cx: [-1.0, -0.75, -0.5, -0.25, 0.0, 0.25, 0.5, 0.75]
steps: [100, 100, 100, 100, 100, 100, 5, 3]

Line by line:

  • W = simd_width_of[DType.float64]() asks how many Float64s fit in one SIMD register on this CPU. Our machine supports AVX-512, so it’s 8. On many laptops it’s 4, and on Apple silicon it’s 2.
  • iota[DType.float64, W](0) makes the vector [0, 1, 2, ...]. Multiplying and adding turns it into W evenly spaced cx values.
  • (x * x + y * y).le(4) compares every lane with 4 and gives a mask of True/False, one per lane. (<= would try to give a single Bool and doesn’t compile for vectors.)
  • still_inside.reduce_or() is True if any lane is still inside. When none are, we stop early.
  • counts += still_inside.cast[DType.int64]() turns True/False into 1/0 and adds it: lanes that are still inside get one more step, escaped lanes stay where they are.

The escaped lanes keep computing (their numbers grow huge and end up as infinity or “not a number”), but their counts don’t change, so the answer is the same as the plain version’s. Doing a little wasted work on a few lanes is the usual price for doing everything in lockstep.

First, let’s make sure the SIMD version draws exactly the same picture. Each row is cut into chunks of W columns. The last chunk may stick out past the edge (72 isn’t a multiple of every possible W), so we only use the lanes that are inside the grid:

from std.math import iota
from std.sys import simd_width_of
comptime WIDTH = 72
comptime HEIGHT = 24
comptime MAX_ITER = 100
comptime SHADES = " .:-=+*%#"
comptime W = simd_width_of[DType.float64]()
def escape_time_simd(
cx: SIMD[DType.float64, W], cy: Float64, max_iter: Int
) -> SIMD[DType.int64, W]:
var x = SIMD[DType.float64, W](0)
var y = SIMD[DType.float64, W](0)
var counts = SIMD[DType.int64, W](0)
for _ in range(max_iter):
var still_inside = (x * x + y * y).le(4)
if not still_inside.reduce_or():
break
counts += still_inside.cast[DType.int64]()
var new_x = x * x - y * y + cx
y = 2 * x * y + cy
x = new_x
return counts
def main():
var step = 2.8 / Float64(WIDTH - 1)
for row in range(HEIGHT):
var cy = -1.2 + 2.4 * Float64(row) / Float64(HEIGHT - 1)
var line = String()
for col in range(0, WIDTH, W):
var cx = -2.15 + iota[DType.float64, W](Float64(col)) * step
var counts = escape_time_simd(cx, cy, MAX_ITER)
for lane in range(W):
if col + lane < WIDTH:
var n = Int(counts[lane])
if n == MAX_ITER:
line += "@"
else:
line += SHADES[byte=min(n // 2, 8)]
print(line.rstrip())

Output:

..........................................................
.............................:::::::-+-:::::::.............
..........................:::::::::::--=#+#+-::::::..........
........................:::::::::::::-=+*###==-::::::::.......
.......................:::::::::::-----=##@@@@#+---::::::::.....
.....................::::::::::-#+%+==%+**#@@@@#*++#=---=%-::....
..................:::::::::::---==#@@#@@@@@@@@@@@@@@@@%#@@#=:::...
..............::::::::::::----=###@@@@@@@@@@@@@@@@@@@@@@#+=--:::..
.......:::::::::-=+==-=++=---==*##@@@@@@@@@@@@@@@@@@@@@@@@@@%+-:::.
..:::::::::::::--==*#@##@#@#*+*#@@@@@@@@@@@@@@@@@@@@@@@@@@@#+--::::
.::::::::::::--===+#@@@@@@@@@@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@##-:::::
:::---=----==++*#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#=--:::::
:::---=----==++*#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#=--:::::
.::::::::::::--===+#@@@@@@@@@@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@##-:::::
..:::::::::::::--==*#@##@#@#*+*#@@@@@@@@@@@@@@@@@@@@@@@@@@@#+--::::
.......:::::::::-=+==-=++=---==*##@@@@@@@@@@@@@@@@@@@@@@@@@@%+-:::.
..............::::::::::::----=###@@@@@@@@@@@@@@@@@@@@@@#+=--:::..
..................:::::::::::---==#@@#@@@@@@@@@@@@@@@@%#@@#=:::...
.....................::::::::::-#+%+==%+**#@@@@#*++#=---=%-::....
.......................:::::::::::-----=##@@@@#+---::::::::.....
........................:::::::::::::-=+*###==-::::::::.......
..........................:::::::::::--=#+#+-::::::..........
.............................:::::::-+-:::::::.............
..........................................................

Character for character the same as Step 2. iota[...](Float64(col)) starts the lane numbers at col, so the chunk covers columns col to col + W - 1, and -2.15 + column * step is the same formula the plain version uses.

Now the timing. Here’s the plain and the SIMD count side by side, three rounds each:

from std.math import iota
from std.sys import simd_width_of
from std.time import perf_counter_ns
comptime MAX_ITER = 200
comptime W = simd_width_of[DType.float64]()
def escape_time(cx: Float64, cy: Float64, max_iter: Int) -> Int:
var x: Float64 = 0
var y: Float64 = 0
for i in range(max_iter):
if x * x + y * y > 4:
return i
var new_x = x * x - y * y + cx
y = 2 * x * y + cy
x = new_x
return max_iter
def escape_time_simd(
cx: SIMD[DType.float64, W], cy: Float64, max_iter: Int
) -> SIMD[DType.int64, W]:
var x = SIMD[DType.float64, W](0)
var y = SIMD[DType.float64, W](0)
var counts = SIMD[DType.int64, W](0)
for _ in range(max_iter):
var still_inside = (x * x + y * y).le(4)
if not still_inside.reduce_or():
break
counts += still_inside.cast[DType.int64]()
var new_x = x * x - y * y + cx
y = 2 * x * y + cy
x = new_x
return counts
def count_plain(width: Int, height: Int) -> Int:
var inside = 0
var step = 2.8 / Float64(width - 1)
for row in range(height):
var cy = -1.2 + 2.4 * Float64(row) / Float64(height - 1)
for col in range(width):
var cx = -2.15 + Float64(col) * step
if escape_time(cx, cy, MAX_ITER) == MAX_ITER:
inside += 1
return inside
def count_simd(width: Int, height: Int) -> Int:
var inside = 0
var step = 2.8 / Float64(width - 1)
for row in range(height):
var cy = -1.2 + 2.4 * Float64(row) / Float64(height - 1)
for col in range(0, width, W):
var cx = -2.15 + iota[DType.float64, W](Float64(col)) * step
var counts = escape_time_simd(cx, cy, MAX_ITER)
for lane in range(W):
if col + lane < width and Int(counts[lane]) == MAX_ITER:
inside += 1
return inside
def main():
for _ in range(3):
var t0 = perf_counter_ns()
var a = count_plain(1600, 1200)
var t1 = perf_counter_ns()
var b = count_simd(1600, 1200)
var t2 = perf_counter_ns()
print("plain:", a, "points inside,", (t1 - t0) // 1_000_000, "ms")
print("simd: ", b, "points inside,", (t2 - t1) // 1_000_000, "ms")

Here’s one run on our test machine (the 4-core Xeon VM, 8 lanes of Float64):

plain: 435444 points inside, 301 ms
simd: 435444 points inside, 58 ms
plain: 435444 points inside, 244 ms
simd: 435444 points inside, 58 ms
plain: 435444 points inside, 242 ms
simd: 435444 points inside, 58 ms

Same count, so the same answer. Over several runs the plain version took 236 to 301 ms and the SIMD version 57 to 58 ms: about 4 times faster on this machine. (The first plain round is often a little slower while the machine warms up.)

Why 4 and not 8, with 8 lanes? A chunk keeps looping until its slowest lane escapes, so lanes next to the set’s edge drag their neighbours along. And the plain version isn’t slow to begin with: it’s already compiled to machine code. On a CPU with 4 or 2 Float64 lanes, expect a smaller gain. Measure on your own machine before you believe any number, ours included.

  • Zoom in. Change the window to something like cx from -0.8 to -0.7 and cy from 0.05 to 0.15, and raise MAX_ITER. The edge is endlessly detailed.
  • Use all cores with parallelize over rows, each row writing into its own slot of a result list. Time it against the SIMD version.
  • Colors. Print ANSI color codes (like "\x1b[34m" for blue) instead of characters.
  • Save a real image. The PGM format is just a short header and a list of numbers, so you can write one with open("mandel.pgm", "w") and open it in most image viewers.

Using escape_time from Step 1, count how many points of the 72 by 24 ASCII grid are inside the set (MAX_ITER = 100).

Hint: the same two loops as Step 2, but add 1 to a counter instead of building a line.

Show solution
def escape_time(cx: Float64, cy: Float64, max_iter: Int) -> Int:
var x: Float64 = 0
var y: Float64 = 0
for i in range(max_iter):
if x * x + y * y > 4:
return i
var new_x = x * x - y * y + cx
y = 2 * x * y + cy
x = new_x
return max_iter
def main():
var inside = 0
var step = 2.8 / 71.0
for row in range(24):
var cy = -1.2 + 2.4 * Float64(row) / 23.0
for col in range(72):
if escape_time(-2.15 + Float64(col) * step, cy, 100) == 100:
inside += 1
print(inside, "of", 72 * 24, "points are inside")

Output:

374 of 1728 points are inside

Count the @ characters in the Step 2 picture and you’ll get the same number.

W doesn’t have to be the register width. Change the Step 4 program to comptime W = 4 and run it. Do the step counts change?

Hint: W is a compile-time constant, so changing it gives you a different, still correct, program.

Show solution
from std.math import iota
comptime W = 4
def escape_time_simd(
cx: SIMD[DType.float64, W], cy: Float64, max_iter: Int
) -> SIMD[DType.int64, W]:
var x = SIMD[DType.float64, W](0)
var y = SIMD[DType.float64, W](0)
var counts = SIMD[DType.int64, W](0)
for _ in range(max_iter):
var still_inside = (x * x + y * y).le(4)
if not still_inside.reduce_or():
break
counts += still_inside.cast[DType.int64]()
var new_x = x * x - y * y + cx
y = 2 * x * y + cy
x = new_x
return counts
def main():
var cx = iota[DType.float64, W](0) * 0.25 + 0.0
print("cx: ", cx)
print("steps:", escape_time_simd(cx, 0.0, 100))

Output:

cx: [0.0, 0.25, 0.5, 0.75]
steps: [100, 100, 5, 3]

These are the last four lanes from Step 4, with exactly the same counts. The width changes how many points are computed together, not the answers. A width bigger than the hardware’s still works; Mojo splits it into several instructions.

  • The Mandelbrot test is x*x + y*y > 4: once a point gets further than 2 from the center, it escapes. Keep new_x separate so y uses the old x.
  • var x: Float64 = 0 avoids mixing Int and Float64; Mojo doesn’t convert between them silently.
  • SIMD[DType.float64, W] runs the same formula on W points at once; simd_width_of picks a width that fits your CPU.
  • Lanes that finish at different times need a mask: .le(4) per lane, reduce_or() to see if any are left, and cast to add 1 only where it’s True.
  • Check the fast version gives the same answer, then time both. On our 4-core test VM, SIMD was about 4 times faster; your CPU will differ.

Next up: Project: Speed Up a Python Script, where you move a slow Python function into Mojo and measure the difference.

Quick check

1. Why does the loop compute new_x before changing y?
2. In the SIMD version, what does still_inside.reduce_or() tell you?
3. With 8 lanes, why was the SIMD version about 4 times faster rather than 8?
4. Why do the timing programs print the number of points inside?