Skip to content

Instantly share code, notes, and snippets.

@zombiecalypse
Created June 25, 2013 20:33
Show Gist options
  • Save zombiecalypse/5862096 to your computer and use it in GitHub Desktop.
Save zombiecalypse/5862096 to your computer and use it in GitHub Desktop.
A stupid way to compute the mandelbrot iteration in Halide (https://github.com/halide/Halide).
/*
* Build as
* g++ mandelbrot.cpp -I /path/to/Halide/include -I /path/to/Halide/apps /path/to/libHalide.a \
* -o mandel -lpthread -ldl -L/usr/lib/x86_64-linux-gnu -lpng12 -I/usr/include/libpng12
*/
#include <Halide.h>
using namespace Halide;
#include <support/image_io.h>
#include <time.h>
#include <iostream>
Var x, y, l, c;
inline Func mandel_step(Func f, Func m0) {
Func g;
Expr r = f(x, y, 0);
Expr i = f(x, y, 1);
g(x, y, l) = select(l == 0,
pow(r, 2) - pow(i, 2) + m0(x,y, 0),
2 * r * i + m0(x,y, 1));
return g;
}
int main() {
const int n_iter = 50;
const int dim = 5000;
Expr scale = static_cast<float>(dim)/4;
Func m0("m0"), mandelbrot("mandel");
m0(x, y, l) = select(l == 0, x - dim/2, y - dim/2)/scale;
m0.compute_root();
Func m[n_iter];
m[0](x, y, l) = m0(x, y, l);
for (int i = 1; i < n_iter; i++) {
m[i](x, y, l) = clamp(mandel_step(m[i-1], m0)(x, y, l), -4.f, 4.f);
}
mandelbrot(x, y, c) = clamp(m[n_iter-1](x, y, c), 0.f, 1.f);
mandelbrot.parallel(x);
clock_t t0 = clock();
mandelbrot.compile_jit();
clock_t t1 = clock();
std::cout << "time to compile: " << t1 - t0 << std::endl;
Image<float> output = mandelbrot.realize(dim, dim, 3);
clock_t t2 = clock();
std::cout << "time to process: " << t2 - t1 << std::endl;
save(output, "mandelbrot.png");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment