take as much work as possible out of the benchmarks and into setup
@@ -6,11 +6,21 @@ import io.improbable.keanu.tensor.dbl.ScalarDoubleTensor;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
@State(Scope.Benchmark)
public class Nd4jDoubleTensorTimesScalar {
+ public DoubleTensor tensor;
+
+ public static DoubleTensor[] scalars = new DoubleTensor[] {
+ Nd4jDoubleTensor.scalar(1.),
+ Nd4jDoubleTensor.scalar(1.).reshape(1),
+ Nd4jDoubleTensor.scalar(1.).reshape(1, 1),
+ new ScalarDoubleTensor(1.)
+ };
+
public enum Operation {
PLUS {
public DoubleTensor apply(DoubleTensor lhs, DoubleTensor rhs) {
@@ -42,42 +52,32 @@ public class Nd4jDoubleTensorTimesScalar {
@Param({"100", "10000", "1000000"})
public double tensorLength;
- @Benchmark
- public long baseline() {
- DoubleTensor scalar = Nd4jDoubleTensor.scalar(1.);
- DoubleTensor tensor = DoubleTensor.arange(0., tensorLength);
- DoubleTensor product = operation.apply(scalar, tensor);
- return product.getLength();
+ @Setup
+ public void createTensor() {
+ tensor = DoubleTensor.arange(0., tensorLength);
}
@Benchmark
- public long rank0() {
- DoubleTensor scalar = Nd4jDoubleTensor.scalar(1.).reshape();
- DoubleTensor tensor = DoubleTensor.arange(0., tensorLength);
- DoubleTensor product = operation.apply(scalar, tensor);
+ public long baseline() {
+ DoubleTensor product = operation.apply(scalars[0], tensor);
return product.getLength();
}
@Benchmark
public long rank1() {
- DoubleTensor scalar = Nd4jDoubleTensor.scalar(1.).reshape(1);
- DoubleTensor tensor = DoubleTensor.arange(0., tensorLength);
- DoubleTensor product = operation.apply(scalar, tensor);
+ DoubleTensor product = operation.apply(scalars[1], tensor);
return product.getLength();
}
@Benchmark
public long rank2() {
- DoubleTensor scalar = Nd4jDoubleTensor.scalar(1.).reshape(1, 1);
- DoubleTensor tensor = DoubleTensor.arange(0., tensorLength);
- DoubleTensor product = operation.apply(scalar, tensor);
+ DoubleTensor product = operation.apply(scalars[2], tensor);
return product.getLength();
}
@Benchmark
public long customScalars() {
- DoubleTensor scalar = new ScalarDoubleTensor(1.);
- DoubleTensor tensor = DoubleTensor.arange(0., tensorLength);
- DoubleTensor product = operation.apply(scalar, tensor);
+ DoubleTensor product = operation.apply(scalars[3], tensor);
return product.getLength();
}
+
}
\ No newline at end of file
