Last active
August 29, 2015 14:00
-
-
Save biboudis/a88a48be7408b3d90192 to your computer and use it in GitHub Desktop.
Test sequential and parallel mandelbrot in Java 8 with JMH. (http://openjdk.java.net/projects/code-tools/jmh/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package benchmark; | |
import java.util.stream.*; | |
import org.openjdk.jmh.annotations.*; | |
import java.util.concurrent.TimeUnit; | |
import java.util.*; | |
@OutputTimeUnit(TimeUnit.NANOSECONDS) | |
@BenchmarkMode(Mode.AverageTime) | |
public class MyBenchmark { | |
// example ported from https://msmvps.com/blogs/jon_skeet/archive/2007/10/03/linq-to-silliness-generating-a-mandelbrot-with-parallel-potential.aspx | |
static int MaxIterations = 1000; | |
static double SampleWidth = 3.2; | |
static double SampleHeight = 2.5; | |
static double OffsetX = -2.1; | |
static double OffsetY = -1.25; | |
static int ImageWidth = 900; | |
static int ImageHeight = (int) (SampleHeight * ImageWidth / SampleWidth); | |
static double[] rowPoints, columnPoints; | |
static { | |
rowPoints = IntStream.range(0, ImageHeight).mapToDouble(i -> i).toArray(); | |
columnPoints = IntStream.range(0, ImageWidth).mapToDouble(i -> i).toArray(); | |
} | |
static int ComputeMandelbrotIndex(double row, double col) { | |
double x = (col * SampleWidth) / ImageWidth + OffsetX; | |
double y = (row * SampleHeight) / ImageHeight + OffsetY; | |
double y0 = y; | |
double x0 = x; | |
for (int i = 0; i < MaxIterations; i++) { | |
if (x * x + y * y >= 4) { | |
return (byte) ((i % 255) + 1); | |
} | |
double xtemp = x * x - y * y + x0; | |
y = 2 * x * y + y0; | |
x = xtemp; | |
} | |
return 0; | |
} | |
@GenerateMicroBenchmark | |
public double[] mandelbrotSeq() { | |
double[] data | |
= DoubleStream.of(rowPoints) | |
.flatMap(rowPoint -> DoubleStream.of(columnPoints) | |
.map(columnPoint -> ComputeMandelbrotIndex(rowPoint, columnPoint))) | |
.toArray(); | |
return data; | |
} | |
@GenerateMicroBenchmark | |
public double[] mandelbrotPar() { | |
double[] data | |
= DoubleStream.of(rowPoints) | |
.parallel() | |
.flatMap(rowPoint -> DoubleStream.of(columnPoints) | |
.map(columnPoint -> ComputeMandelbrotIndex(rowPoint, columnPoint))) | |
.toArray(); | |
return data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment