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