Zaggle: optimizing Mandelbrot

So i was taking my waggle project (a tiny graphics lib that depends on MiniFB only, didn’t go too far) to Zig (zaggle)

I had a Mandelbrot example, thought’d be a great thing to optimize.

The underlying implementations are not really changed, so performance should be similar.
But what I got when benchmarking was this:


(data from waggle are labled with c_, while zaggle is not labeled;
baseline for naively iterating, 4thrd for tiling 4 thread implementation, 4async for tiling 4 std.Io.async implementation;
C version built with -O3, Zig version built with -Doptimize=fast)

You can see that the Zig baseline outperforms the C baseline, even close to 4 threaded C.

I heard that Zig might be faster than C, that it can do more optimization tricks, but didn’t expect this much tbh

Also, here’s the mandelbrot code for both, 'd be grateful if anyone points out any wrong places / gives optimization stratagies.
suxyio/zaggle examples/src/mandelbrot_perf_log.zig
suxyio/waggle examples/mandelbrot.c

Did you compile the C code with Zig, and/or -march=native? And if your C code is spread across multiple source files, are you building with -flto to enable optimization across compilation units?

AFAIK these are the two main differences between C and Zig’s build models. Another smaller issue might be more aggressive optimizations around pointer aliasing in Zig vs C.

But in general, giving the same memory access patterns (e.g. same code structure and data types) and giving the C compiler the same aggressive compilation options that Zig uses by default, I would except nearly byte-by-byte identical output (assuming both compilers are LLVM based) - and that should be true for all compiled languages btw, not just Zig vs C.

Or maybe when on x86 you’re lucky and you hit a sweet spot in Zig’s non-LLVM backend :slight_smile:

PS: looking at the code, this may already be the culprit:

https://codeberg.org/SuXYIO/waggle/src/commit/b2856d5e23a59560697148b8b922fdfaa5726066/examples/mandelbrot.c#L71

… it looks like you’re calling a callback for each pixel from within equa_draw_4thrd, and I guess that function lives in another C source file.

In Zig the per-pixel callback function body will almost certainly be inlined into the caller because Zig builds the entire program as a single compilation unit, while in C it definitely won’t be inlined unless you build with -flto (and even then it’s not guaranteed)… and this inlining may in turn unlock more optimizations (like loop unrolling or vectorization)…

5 Likes

Recompiled waggle with -flto and -march=native, results:

i assume my naming are apparent? Also ran the original C baseline a second time just in case.
And the newly compiled versions performs the same as the original C baseline as you can see.

i added the args via xmake

set_policy("build.optimization.lto", true)
add_cxflags("-march=native")

also looked at the dry run verbose output, not a compiler expert but at least the intended args was added.

Using GCC, might try Zig CC later since it breaks my includes.

1 Like

I think the fact that your C graphs grow so unevenly, compared to the Zig graphs which grow linearly with occasional spikes, suggests that there is some significant (but probably unintended) difference between the underlying implementations.

I took a quick look at both examples’ respective source code and noticed some differences:

  • The C implementation clears the canvas before every iteration.
  • The Zig impl calls mfb_update, while the C impl calls mfb_update_ex.
  • The Zig impl’s draw buffer is stored on the stack, while the C impl’s buffer is dynamically allocated (does data locality have an impact?).

These don’t necessarily explain why the graphs grow so differently (I’d still expect them to exhibit linear growth), but if you want a meaningful comparison, you should probably carefully review both implementations line by line and verify that they really are as identical as possible.

You might also need to consider other factors, such as asking whether C cabs() and Zig Complex.magnitude() are truly identical. Zig’s implementation is literally just @sqrt(self.re * self.re + self.im * self.im). The C implementation on the other hand probably defers to hypot() from <math.h>, which tries to avoid precision loss and must handle erroneous/special values like inf, NaN and subnormals and is a lot more complicated as a consequence. See the musl source code for hypot() for yourself.

I actually suspect that this math function might be the main culprit; it would explain why the graph sometimes declines (more values can take the fast path than the previous iteration). Try replacing your cabs() call with sqrt(creal(x) * creal(x) + cimag(x) * cimag(x)) and see if that makes a difference.

6 Likes

I haven’t looked in details but I am not sure if your C code is well optimized.
You may want to check my implementation: https://codeberg.org/jangorecki/marth/src/branch/master/src/mandelbrot.c
it is actually very basic, but things like swapping inner loop to be outer loop can increase cache efficiency.

1 Like

I played around with @floooh and @castholm’s suggestions. Dumping everyting into one translation unit, and making the relevant functions static, inlined the callback, but didn’t fix the performance disparity. Replacing

bool mandelbrot_equa(coord_t coord) {
    coord_t newc = coord_transform_view(
        coord,
        coord_add(center, (coord_t){ -1.0 * scale, -1.0 * scale }),
        coord_add(center, (coord_t){ 1.0 * scale, 1.0 * scale })
    );
    double complex c = newc.x + newc.y * I;
    double complex z = 0 + 0 * I;
    for (int i = 0; i < diverge_iter; i++)
        z = z * z + c;
    return cabs(z) < diverge_thresh;
}

with a direct implementation

bool mandelbrot_equa(coord_t coord) {
    coord_t newc = coord_transform_view(
        coord,
        coord_add(center, (coord_t){ -1.0 * scale, -1.0 * scale }),
        coord_add(center, (coord_t){ 1.0 * scale, 1.0 * scale })
    );
    coord_t z = { 0 };
    for (int i = 0; i < diverge_iter; i++) {
        z = (coord_t){
            z.x * z.x - z.y * z.y + newc.x,
            z.x * z.y + z.y * z.x + newc.y,
        };
    }
    return sqrt(z.x * z.x + z.y * z.y) < diverge_thresh;
}

finally did the trick. I’ve never touched C99’s complex.h before, so I’m not sure what the issue is here. Just doing cabs(z) → sqrt(creal(z) * creal(z) + cimag(z) * cimag(z)) didn’t change anything.

4 Likes

Considering you are just doing a comparison, why not compare the squared distances instead of taking the square root?

Or said another way, I would use return (z.x * z.x + z.y * z.y) < (diverge_thresh * diverge_thresh);

2 Likes

Yeah, that’s definitely better. But their Zig code also writes the comparison this way, and I wasn’t thinking about optimizing, just trying to find why the C was compiling so differently.

2 Likes

Excellent digging! Let’s check further with Godbolt:

#include <complex.h>

const int diverge_thresh = 2;

int mandelbrot_equa_1(double newc_x, double newc_y, int diverge_iter) {
    double complex c = newc_x + newc_y * I;
    double complex z = 0 + 0 * I;
    for (int i = 0; i < diverge_iter; i++)
        z = z * z + c;
    return cabs(z) < diverge_thresh;
}

int mandelbrot_equa_2(double newc_x, double newc_y, int diverge_iter) {
    double complex c = newc_x + newc_y * I;
    double complex z = 0 + 0 * I;
    for (int i = 0; i < diverge_iter; i++)
        z = z * z + c;
    return __builtin_sqrt(creal(z) * creal(z) + cimag(z) * cimag(z)) < diverge_thresh;
}

int mandelbrot_equa_3(double newc_x, double newc_y, int diverge_iter) {
    double z_x = 0;
    double z_y = 0;
    for (int i = 0; i < diverge_iter; i++) {
        z_x = z_x * z_x - z_y * z_y + newc_x;
        z_y = z_x * z_y + z_x * z_y + newc_y;
    }
    return __builtin_sqrt(z_x * z_x + z_y * z_y) < diverge_thresh;
}
  • 1 contains calls cabs and __muldc3.
  • 2 contains a call to __muldc3.
  • 3 contains no calls.

What is __muldc3? It’s a compiler-supplied function for multiplying complex numbers in a way that ensures that infinity and NaN are handled with correct semantics and in accordance with the C spec (the naive implementation does not handle these special values). Here’s a link to Zig’s compiler-rt implementation. You can probably see why this is slower than plain multiplication and addition.

If we compile with -fcx-limited-range (or -ffinite-math-only), the __muldc3 calls go away.

3 Likes

Man, never thought stdlib’d be so performance heavy, footgun for sure!
nocomplex using:

bool mandelbrot_equa(coord_t coord) {
    coord_t c = coord_transform_view(
        coord,
        coord_add(center, (coord_t){-1.0 * scale, -1.0 * scale}),
        coord_add(center, (coord_t){1.0 * scale, 1.0 * scale}));
    coord_t z = {0, 0};
    for (int i = 0; i < diverge_iter; i++) {
        z = (coord_t){
            z.x * z.x - z.y * z.y,
            2 * z.x * z.y,
        };
        z.x += c.x;
        z.y += c.y;
    }

    double re = z.x;
    double im = z.y;
    return re * re + im * im < diverge_thresh * diverge_thresh;
}

now the C versions are as performant as Zig versions (even slightly faster)

Also tested replacing cabs only, basically same as the old c_baseline.

tested, no apparent impact

Thanks again to all of you, learnt a lot!

2 Likes

Got to love how this community, when given an opportunity to brag about Zig’s speed … don’t. Instead, they optimise the version that Zig is being measured against.

None of you will ever make it big in business. :wink::+1:

6 Likes