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 47 @Benchmark log2(int reps)48 long log2(int reps) { 49 long tmp = 0; 50 for (int i = 0; i < reps; i++) { 51 int j = i & ARRAY_MASK; 52 tmp += Double.doubleToRawLongBits(DoubleMath.log2(positiveDoubles[j])); 53 } 54 return tmp; 55 } 56 57 @Benchmark factorial(int reps)58 long factorial(int reps) { 59 long tmp = 0; 60 for (int i = 0; i < reps; i++) { 61 int j = i & ARRAY_MASK; 62 tmp += Double.doubleToRawLongBits(DoubleMath.factorial(factorials[j])); 63 } 64 return tmp; 65 } 66 67 @Benchmark isMathematicalInteger(int reps)68 int isMathematicalInteger(int reps) { 69 int tmp = 0; 70 for (int i = 0; i < reps; i++) { 71 int j = i & ARRAY_MASK; 72 if (DoubleMath.isMathematicalInteger(doubles[j])) { 73 tmp++; 74 } 75 } 76 return tmp; 77 } 78 79 @Benchmark isPowerOfTwo(int reps)80 int isPowerOfTwo(int reps) { 81 int tmp = 0; 82 for (int i = 0; i < reps; i++) { 83 int j = i & ARRAY_MASK; 84 if (DoubleMath.isPowerOfTwo(doubles[j])) { 85 tmp++; 86 } 87 } 88 return tmp; 89 } 90 } 91