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.core; 19 20 import org.apache.commons.rng.UniformRandomProvider; 21 import org.openjdk.jmh.annotations.Benchmark; 22 import org.openjdk.jmh.annotations.Scope; 23 import org.openjdk.jmh.annotations.State; 24 25 /** 26 * Executes benchmark to compare the speed of generation of random numbers from the 27 * various source providers for {@link UniformRandomProvider#nextBytes(byte[])}. 28 */ 29 public class NextBytesGenerationPerformance extends AbstractBenchmark { 30 /** 31 * The value. This is a pre-allocated array. Must NOT be final to prevent JVM 32 * optimisation! 33 */ 34 private byte[] value = new byte[BaselineGenerationPerformance.NEXT_BYTES_SIZE]; 35 36 /** 37 * The benchmark state (retrieve the various "RandomSource"s). 38 */ 39 @State(Scope.Benchmark) 40 public static class Sources extends BaselineSources { 41 /** {@inheritDoc} */ 42 @Override 43 protected UniformRandomProvider createBaseline() { 44 return BaselineUtils.getNextBytes(); 45 } 46 } 47 48 /** 49 * Baseline for a JMH method call with no return value. 50 */ 51 @Benchmark 52 public void baselineVoid() { 53 // Do nothing, this is a baseline 54 } 55 56 /** 57 * Baseline for a JMH method call returning a {@code byte[]}. 58 * 59 * @return the value 60 */ 61 @Benchmark 62 public byte[] baselineBytes() { 63 return value; 64 } 65 66 /** 67 * Exercise the {@link UniformRandomProvider#nextBytes(byte[])} method. 68 * 69 * @param sources Source of randomness. 70 * @return the boolean 71 */ 72 @Benchmark 73 public byte[] nextBytes(Sources sources) { 74 // The array allocation is not part of the benchmark. 75 sources.getGenerator().nextBytes(value); 76 return value; 77 } 78 }