1 /* 2 * Copyright (C) 2011 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.math; 18 19 import static com.google.common.math.MathBenchmarking.ARRAY_MASK; 20 import static com.google.common.math.MathBenchmarking.ARRAY_SIZE; 21 import static com.google.common.math.MathBenchmarking.randomDouble; 22 import static com.google.common.math.MathBenchmarking.randomPositiveDouble; 23 24 import com.google.caliper.BeforeExperiment; 25 import com.google.caliper.Benchmark; 26 import com.google.caliper.Param; 27 import java.math.RoundingMode; 28 29 /** 30 * Benchmarks for the rounding methods of {@code DoubleMath}. 31 * 32 * @author Louis Wasserman 33 */ 34 public class DoubleMathRoundingBenchmark { 35 private static final double[] doubleInIntRange = new double[ARRAY_SIZE]; 36 private static final double[] doubleInLongRange = new double[ARRAY_SIZE]; 37 private static final double[] positiveDoubles = new double[ARRAY_SIZE]; 38 39 @Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"}) 40 RoundingMode mode; 41 42 @BeforeExperiment setUp()43 void setUp() { 44 for (int i = 0; i < ARRAY_SIZE; i++) { 45 doubleInIntRange[i] = randomDouble(Integer.SIZE - 2); 46 doubleInLongRange[i] = randomDouble(Long.SIZE - 2); 47 positiveDoubles[i] = randomPositiveDouble(); 48 } 49 } 50 51 @Benchmark roundToInt(int reps)52 int roundToInt(int reps) { 53 int tmp = 0; 54 for (int i = 0; i < reps; i++) { 55 int j = i & ARRAY_MASK; 56 tmp += DoubleMath.roundToInt(doubleInIntRange[j], mode); 57 } 58 return tmp; 59 } 60 61 @Benchmark roundToLong(int reps)62 long roundToLong(int reps) { 63 long tmp = 0; 64 for (int i = 0; i < reps; i++) { 65 int j = i & ARRAY_MASK; 66 tmp += DoubleMath.roundToLong(doubleInLongRange[j], mode); 67 } 68 return tmp; 69 } 70 71 @Benchmark roundToBigInteger(int reps)72 int roundToBigInteger(int reps) { 73 int tmp = 0; 74 for (int i = 0; i < reps; i++) { 75 int j = i & ARRAY_MASK; 76 tmp += DoubleMath.roundToBigInteger(positiveDoubles[j], mode).intValue(); 77 } 78 return tmp; 79 } 80 81 @Benchmark log2Round(int reps)82 int log2Round(int reps) { 83 int tmp = 0; 84 for (int i = 0; i < reps; i++) { 85 int j = i & ARRAY_MASK; 86 tmp += DoubleMath.log2(positiveDoubles[j], mode); 87 } 88 return tmp; 89 } 90 } 91