I am always interested in some of the subtle effects that coding can have on not just the behavior of code, but also its performance. Recently, I stumbled across some benchmarking code – I cannot recall how I actually found it. It was not written in C, so I translated it.
In the process, I realized that a literal translation might not be ideal …
The code is to do with Mandelbrot sets. My first C translation looked like this:
int mandelbrot(float a)
{
float b;
int iterations = 50;
int i;
b = a;
for (i=1; i<=iterations; i++)
{
if (abs(a) > 2)
return (i - 1);
a = pow(a, 2) + b;
}
return (iterations);
}
I then saw a couple of optimizations that I could make:
#define ITERATIONS 50
int mandelbrot(float a)
{
float b;
int i;
b = a;
for (i=1; i<=ITERATIONS; i++)
{
if (abs(a) > 2)
return (i - 1);
a = a * a + b;
}
return (ITERATIONS);
}
I made it clear that iterations was a constant. I could have simply qualified it with const, but I chose to use #define. Call me old fashioned if you like. Both would most likely produce the same result. A good compiler may well optimize this without my help.
Since the code was translated from a language that included an exponentiation operator, using the pow() library function seemed logical, as C has no such operator. As a is simply squared, multiplication seemed better. Again, a smart compiler may well have addressed this.
I then saw another possible enhancement that might be effective:
#define ITERATIONS 50
int mandelbrot(float a)
{
float b;
int i;
b = a;
for (i=1; i<=ITERATIONS; i++)
{
if (abs(b) > 2)
return (i - 1);
b = b * b + a;
}
return (ITERATIONS);
}
Does this improve matters? If so, why? Please let me know your thoughts by email or comment. Sorry, no prizes, but I will follow up this posting with my further thoughts sometime soon.
Preparing Recommendations
Comments (↓ Add Your Own)
6 Comments on this Post
Commented on 10:57 AM, Oct 22, 2012
By Peter Bushell
Commented on 12:55 PM, Oct 22, 2012
By Colin Walls
Commented on 1:48 PM, Oct 25, 2012
By Peter Bushell
Commented on 1:56 PM, Oct 25, 2012
By Colin Walls
Commented on 8:47 AM, Nov 4, 2012
By Grygorii Tertychnyi
Commented on 9:01 AM, Nov 5, 2012
By Colin Walls
Add Your Comment
Please complete the following information to comment or sign in.