From 8a5283cf4e45a87e213066692673e082312db083 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Mon, 29 Dec 2025 08:57:33 +0900 Subject: [PATCH] benchmark: terminal version of mandelbrot Optimized to avoid Math.sqrt by squaring the threshold (sqrt(x) < 1000 => x < 1000000) and caching zr*zr/zi*zi to avoid redundant computation. 29% faster than naive version. Co-authored-by: Claude --- benchmark/bm_mandel_term.rb | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 benchmark/bm_mandel_term.rb diff --git a/benchmark/bm_mandel_term.rb b/benchmark/bm_mandel_term.rb new file mode 100644 index 000000000..460c2a6b9 --- /dev/null +++ b/benchmark/bm_mandel_term.rb @@ -0,0 +1,34 @@ +def mandelbrot(c_r, c_i) + limit=95 + iterations=0 + cr = (c_r * 100).to_i + ci = (c_i * 100).to_i + zr = zi = 0 + # Avoid sqrt by squaring the threshold: sqrt(x) < 1000 => x < 1000000 + while iterations= 1000000 + zr, zi = (zr2-zi2)/100+cr, (zr*zi*2)/100+ci + iterations+=1 + end + return iterations +end + +def mandel_calc(min_r, min_i, max_r, max_i, res) + cur_i = min_i + while cur_i > max_i + putc "|" + cur_r = min_r + while cur_r < max_r + ch = 127 - mandelbrot(cur_r, cur_i) + putc ch # Use putc with integer - no string allocation! + cur_r += res + end + putc "|" + putc "\n" + cur_i -= res + end +end + +mandel_calc(-2, 1, 1, -1, 0.04)