View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.rng.examples.jmh.distribution;
19  
20  import org.openjdk.jmh.annotations.Benchmark;
21  import org.openjdk.jmh.annotations.BenchmarkMode;
22  import org.openjdk.jmh.annotations.Mode;
23  import org.openjdk.jmh.annotations.Warmup;
24  import org.openjdk.jmh.annotations.Measurement;
25  import org.openjdk.jmh.annotations.State;
26  import org.openjdk.jmh.annotations.Fork;
27  import org.openjdk.jmh.annotations.Scope;
28  import org.openjdk.jmh.annotations.OutputTimeUnit;
29  import org.openjdk.jmh.infra.Blackhole;
30  import java.util.concurrent.TimeUnit;
31  import java.util.Random;
32  
33  /**
34   * Benchmark for {@link Random#nextGaussian()} in order to compare
35   * the speed of generation of normally-distributed random numbers.
36   */
37  @BenchmarkMode(Mode.AverageTime)
38  @OutputTimeUnit(TimeUnit.MICROSECONDS)
39  @Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
40  @Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
41  @State(Scope.Benchmark)
42  @Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
43  public class NextGaussianPerformance {
44      /** Number of samples per run. */
45      private static final int NUM_SAMPLES = 10000000;
46      /** JDK's generator. */
47      private final Random random = new Random();
48      /**
49       * Exercises the JDK's Gaussian sampler.
50       *
51       * @param bh Data sink.
52       */
53      private void runSample(Blackhole bh) {
54          for (int i = 0; i < NUM_SAMPLES; i++) {
55              bh.consume(random.nextGaussian());
56          }
57      }
58  
59      // Benchmarks methods below.
60  
61      /**
62       * @param bh Data sink.
63       */
64      @Benchmark
65      public void runJDKRandomGaussianSampler(Blackhole bh) {
66          runSample(bh);
67      }
68  }