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.randomDouble; 23 import static com.google.common.math.MathBenchmarking.randomPositiveDouble; 24 25 import com.google.caliper.BeforeExperiment; 26 import com.google.caliper.Benchmark; 27 28 /** 29 * Tests for the non-rounding methods of {@code DoubleMath}. 30 * 31 * @author Louis Wasserman 32 */ 33 public class DoubleMathBenchmark { 34 private static final double[] positiveDoubles = new double[ARRAY_SIZE]; 35 private static final int[] factorials = new int[ARRAY_SIZE]; 36 private static final double [] doubles = new double[ARRAY_SIZE]; 37 38 @BeforeExperiment setUp()39 void setUp() { 40 for (int i = 0; i < ARRAY_SIZE; i++) { 41 positiveDoubles[i] = randomPositiveDouble(); 42 doubles[i] = randomDouble(Long.SIZE); 43 factorials[i] = RANDOM_SOURCE.nextInt(100); 44 } 45 } 46 log2(int reps)47 @Benchmark long log2(int reps) { 48 long tmp = 0; 49 for (int i = 0; i < reps; i++) { 50 int j = i & ARRAY_MASK; 51 tmp += Double.doubleToRawLongBits(DoubleMath.log2(positiveDoubles[j])); 52 } 53 return tmp; 54 } 55 factorial(int reps)56 @Benchmark long factorial(int reps) { 57 long tmp = 0; 58 for (int i = 0; i < reps; i++) { 59 int j = i & ARRAY_MASK; 60 tmp += Double.doubleToRawLongBits(DoubleMath.factorial(factorials[j])); 61 } 62 return tmp; 63 } 64 isMathematicalInteger(int reps)65 @Benchmark int isMathematicalInteger(int reps) { 66 int tmp = 0; 67 for (int i = 0; i < reps; i++) { 68 int j = i & ARRAY_MASK; 69 if (DoubleMath.isMathematicalInteger(doubles[j])) { 70 tmp++; 71 } 72 } 73 return tmp; 74 } 75 isPowerOfTwo(int reps)76 @Benchmark int isPowerOfTwo(int reps) { 77 int tmp = 0; 78 for (int i = 0; i < reps; i++) { 79 int j = i & ARRAY_MASK; 80 if (DoubleMath.isPowerOfTwo(doubles[j])) { 81 tmp++; 82 } 83 } 84 return tmp; 85 } 86 } 87