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 com.google.common.math.DoubleMath; 28 29 import java.math.RoundingMode; 30 31 /** 32 * Benchmarks for the rounding methods of {@code DoubleMath}. 33 * 34 * @author Louis Wasserman 35 */ 36 public class DoubleMathRoundingBenchmark { 37 private static final double[] doubleInIntRange = new double[ARRAY_SIZE]; 38 private static final double[] doubleInLongRange = new double[ARRAY_SIZE]; 39 private static final double[] positiveDoubles = new double[ARRAY_SIZE]; 40 41 @Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"}) 42 RoundingMode mode; 43 44 @BeforeExperiment 45 void setUp() { 46 for (int i = 0; i < ARRAY_SIZE; i++) { 47 doubleInIntRange[i] = randomDouble(Integer.SIZE - 2); 48 doubleInLongRange[i] = randomDouble(Long.SIZE - 2); 49 positiveDoubles[i] = randomPositiveDouble(); 50 } 51 } 52 53 @Benchmark int roundToInt(int reps) { 54 int tmp = 0; 55 for (int i = 0; i < reps; i++) { 56 int j = i & ARRAY_MASK; 57 tmp += DoubleMath.roundToInt(doubleInIntRange[j], mode); 58 } 59 return tmp; 60 } 61 62 @Benchmark 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 int roundToBigInteger(int reps) { 72 int tmp = 0; 73 for (int i = 0; i < reps; i++) { 74 int j = i & ARRAY_MASK; 75 tmp += DoubleMath.roundToBigInteger(positiveDoubles[j], mode).intValue(); 76 } 77 return tmp; 78 } 79 80 @Benchmark int log2Round(int reps) { 81 int tmp = 0; 82 for (int i = 0; i < reps; i++) { 83 int j = i & ARRAY_MASK; 84 tmp += DoubleMath.log2(positiveDoubles[j], mode); 85 } 86 return tmp; 87 } 88 } 89