Skip to content

Instantly share code, notes, and snippets.

@srikumarks
Last active May 18, 2023 15:02
Show Gist options
  • Save srikumarks/3e26bce926d15b584f2a89ec6d83ff4d to your computer and use it in GitHub Desktop.
Save srikumarks/3e26bce926d15b584f2a89ec6d83ff4d to your computer and use it in GitHub Desktop.
Julia mandelbrot for benchmarking against Python/Mojo
function mandelbrot_kernel(c, max_iter)
z = c
for i in 1:max_iter
z = z * z + c
if abs2(z) > 4
return i-1
end
end
return max_iter
end
function mandelbrot(;xmin = -2.25, xmax = 0.75, xn = 450, ymin = -1.25, ymax = 1.25, yn = 375, max_iter = 200)
dx = (xmax - xmin) / xn
dy = (ymax - ymin) / yn
return [mandelbrot_kernel(Complex(x,y), max_iter) for y in ymin:dy:ymax, x in xmin:dx:xmax]
end
using BenchmarkTools
@benchmark mandelbrot()
# BenchmarkTools.Trial: 172 samples with 1 evaluation.
# Range (min … max): 25.824 ms … 38.800 ms ┊ GC (min … max): 0.00% … 0.00%
# Time (median): 27.185 ms ┊ GC (median): 0.00%
# Time (mean ± σ): 29.104 ms ± 3.357 ms ┊ GC (mean ± σ): 0.27% ± 1.30%
#
# █▆ ▄▅
# ▅██▆███▆▃▆▄▄▃▃▃▃▃▁▃▁▃▁▃▁▃▁▁▁▁▁▃▃▆▄▃█▆▃▄▇▄▁▃▁▃▃▁▁▃▃▁▃▁▁▁▁▃▁▃ ▃
# 25.8 ms Histogram: frequency by time 37.4 ms <
# On same machine with python 3.10.8 I get 1150ms median-ish.
# Multi-threaded version.
function mandelbrot_mt(;xmin = -2.25, xmax = 0.75, xn = 450, ymin = -1.25, ymax = 1.25, yn = 375, max_iter = 200)
dx = (xmax - xmin) / xn
dy = (ymax - ymin) / yn
result = zeros(UInt32, (yn,xn))
Threads.@threads for j = 1:yn
y = ymin + dy * (j-1)
for i = 1:xn
x = xmin + dx * (i-1)
@inbounds result[j,i] = mandelbrot_kernel(Complex(x,y), max_iter)
end
end
return result
end
@benchmark mandelbrot_mt()
# Starting julia with "julia --threads=16" gets me the following benchmark result on the same machine.
# BenchmarkTools.Trial: 1010 samples with 1 evaluation.
# Range (min … max): 4.201 ms … 14.436 ms ┊ GC (min … max): 0.00% … 0.00%
# Time (median): 4.807 ms ┊ GC (median): 0.00%
# Time (mean ± σ): 4.935 ms ± 575.673 μs ┊ GC (mean ± σ): 0.70% ± 3.91%
#
# ▁▃█▆█▆▄▃▁▂
# ▃▃▅▅▆▇██████████▇▆▆▆▆▅▄▄▅▃▃▃▃▃▃▃▂▃▂▃▂▁▁▂▂▂▂▁▁▂▁▂▁▂▂▂▁▂▁▂▁▁▂ ▄
# 4.2 ms Histogram: frequency by time 7.26 ms <
#
# Memory estimate: 667.91 KiB, allocs estimate: 99.
@Nicholaswogan
Copy link

Do you have a SIMD version yet for comparison?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment