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.RANDOM_SOURCE; 22 import static com.google.common.math.MathBenchmarking.randomNonZeroBigInteger; 23 import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger; 24 25 import com.google.caliper.BeforeExperiment; 26 import com.google.caliper.Benchmark; 27 import com.google.caliper.Param; 28 import java.math.RoundingMode; 29 30 /** 31 * Benchmarks for the rounding methods of {@code IntMath}. 32 * 33 * @author Louis Wasserman 34 */ 35 public class IntMathRoundingBenchmark { 36 private static final int[] positive = new int[ARRAY_SIZE]; 37 private static final int[] nonzero = new int[ARRAY_SIZE]; 38 private static final int[] ints = new int[ARRAY_SIZE]; 39 40 @BeforeExperiment setUp()41 void setUp() { 42 for (int i = 0; i < ARRAY_SIZE; i++) { 43 positive[i] = randomPositiveBigInteger(Integer.SIZE - 2).intValue(); 44 nonzero[i] = randomNonZeroBigInteger(Integer.SIZE - 2).intValue(); 45 ints[i] = RANDOM_SOURCE.nextInt(); 46 } 47 } 48 49 @Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"}) 50 RoundingMode mode; 51 52 @Benchmark log2(int reps)53 int log2(int reps) { 54 int tmp = 0; 55 for (int i = 0; i < reps; i++) { 56 int j = i & ARRAY_MASK; 57 tmp += IntMath.log2(positive[j], mode); 58 } 59 return tmp; 60 } 61 62 @Benchmark log10(int reps)63 int log10(int reps) { 64 int tmp = 0; 65 for (int i = 0; i < reps; i++) { 66 int j = i & ARRAY_MASK; 67 tmp += IntMath.log10(positive[j], mode); 68 } 69 return tmp; 70 } 71 72 @Benchmark sqrt(int reps)73 int sqrt(int reps) { 74 int tmp = 0; 75 for (int i = 0; i < reps; i++) { 76 int j = i & ARRAY_MASK; 77 tmp += IntMath.sqrt(positive[j], mode); 78 } 79 return tmp; 80 } 81 82 @Benchmark divide(int reps)83 int divide(int reps) { 84 int tmp = 0; 85 for (int i = 0; i < reps; i++) { 86 int j = i & ARRAY_MASK; 87 tmp += IntMath.divide(ints[j], nonzero[j], mode); 88 } 89 return tmp; 90 } 91 } 92