Use library functionality
Mandelbrot images are calculated with complex numbers. C++ offers the <complex> header which contains a template for generating complex numbers out of floats or other numeric types.
Initialize at definition
Many compilers can give you warnings about code paths with uninitialized variables but in general it might be good to zero initialize your r, g, and b values to zero at the beginning of the getColor function. This also allows to remove all later zero assignments in the ifs.
Cascading ifs
Often it is a bad idea to cascade ifs in the way you have done.
Since your code uses equal spacing in multiples of 16 you could instead use a switch:
if(iterations < 0) {
} else {
switch(iterations / 16) {
case 0: // deal with 0-15
break;
case 1: // deal with 16-31
break;
case 2: // deal with 32-47
/* no break! */
case 3: // deal with 48-63
break;
default: // deal with iterations >= 64
}
}
Parallelize
The results of different pixels are independent of each other. This screams for parallelization. It might suffice to use OpenMP's parallel for.
Misc
- use
++counterinstead ofcounter += 1;for incrementing (likely to be optimized by compiler) - use
square(T x) { return x * x; }instead ofpow(x, 2.0)(I have seenpow(x, 2.0)compiled to a call topoweven on optimizing compilers;powis one of the slowest arithmetic functions