From 73850281d75235cac5dc192a2f559f5fba36ec7d Mon Sep 17 00:00:00 2001
From: Claude Heiland-Allen
Date: Fri, 20 Dec 2013 21:15:57 +0000
Subject: [PATCH] Escaping a loop early: ``break''.
When we increased the resolution, our program took noticeably longer to
render each image. We can speed it up. Our program currently keeps
iterating to the maximum iterations limit for every pixel, only then
checking if it didn't exceed the escape radius. But if any iterate along
the way exceeded the escape radius, we know that it's already well on the
way to infinity. If we check each time through the loop, then we can
stop looping, with a ``break'' statement -- it makes the control flow
pass immediately to the statement following the loop body.
This simple optimization makes our program four times faster for the
initial view:
$ time ./mandelbrot -0.75 0 1.25 > mandelbrot.pgm
real 0m6.276s
user 0m6.260s
sys 0m0.016s
$ time ./mandelbrot -0.75 0 1.25 > mandelbrot.pgm
real 0m1.593s
user 0m1.584s
sys 0m0.004s
$
---
mandelbrot.c | 3 +++
1 file changed, 3 insertions(+)
diff --git a/mandelbrot.c b/mandelbrot.c
index b47ff44..57b0b7e 100644
--- a/mandelbrot.c
+++ b/mandelbrot.c
@@ -22,6 +22,9 @@ int main(int argc, char **argv) {
complex float z = 0;
for (int n = 0; n < maximum_iterations; ++n) {
z = z * z + c;
+ if (cabs(z) > escape_radius) {
+ break;
+ }
}
if (cabs(z) <= escape_radius) {
putchar(0);
--
2.1.4