Guest User

Singleton benchmark

a guest
Jul 10th, 2016
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. /* MAIN CLASS */
  2. package dk.xakeps.benchmarks.instancespeed;
  3.  
  4. import org.openjdk.jmh.annotations.*;
  5. import org.openjdk.jmh.runner.Runner;
  6. import org.openjdk.jmh.runner.RunnerException;
  7. import org.openjdk.jmh.runner.options.Options;
  8. import org.openjdk.jmh.runner.options.OptionsBuilder;
  9.  
  10. import java.util.concurrent.TimeUnit;
  11.  
  12. @State(Scope.Thread)
  13. @BenchmarkMode(Mode.Throughput)
  14. @OutputTimeUnit(TimeUnit.NANOSECONDS)
  15. public class Main {
  16.     private static Main instance;
  17.  
  18.     public static Main getInstance() {
  19.         if(instance == null) {
  20.             instance = new Main();
  21.         }
  22.         return instance;
  23.     }
  24.  
  25.     @Benchmark
  26.     public void constructorTest() {
  27.         new TestClass(this);
  28.     }
  29.  
  30.     @Benchmark
  31.     public void instanceTest() {
  32.         TestClass.getInstance();
  33.     }
  34.  
  35.     public static void main(String[] args) throws RunnerException {
  36.         Options options = new OptionsBuilder()
  37.                 .include(Main.class.getSimpleName())
  38.                 .warmupIterations(10)
  39.                 .measurementIterations(5)
  40.                 .forks(5)
  41.                 .build();
  42.         new Runner(options).run();
  43.     }
  44. }
  45.  
  46. /* TESTING CLASS */
  47. package dk.xakeps.benchmarks.instancespeed;
  48.  
  49. public class TestClass {
  50.     private Main mainClass;
  51.     private static final class Holder {
  52.         static final TestClass instance = new TestClass();
  53.     }
  54.  
  55.     private TestClass() {
  56.  
  57.     }
  58.  
  59.     public TestClass(Main main) {
  60.         this.mainClass = main;
  61.     }
  62.  
  63.     public static TestClass getInstance() {
  64.         return Holder.instance;
  65.     }
  66. }
  67.  
  68. /* RESULTS */
  69. /*
  70. Result "constructorTest":
  71.   3,743 ±(99.9%) 0,240 ops/ns [Average]
  72.   (min, avg, max) = (3,208, 3,743, 4,157), stdev = 0,321
  73.   CI (99.9%): [3,503, 3,983] (assumes normal distribution)
  74.  
  75. Result "instanceTest":
  76.   3,762 ±(99.9%) 0,088 ops/ns [Average]
  77.   (min, avg, max) = (3,515, 3,762, 3,919), stdev = 0,117
  78.   CI (99.9%): [3,675, 3,850] (assumes normal distribution)
  79.  
  80.  
  81. # Run complete. Total time: 00:02:32
  82.  
  83. Benchmark              Mode  Cnt  Score   Error   Units
  84. Main.constructorTest  thrpt   25  3,743 ± 0,240  ops/ns
  85. Main.instanceTest     thrpt   25  3,762 ± 0,088  ops/ns
  86.  
  87. HIGHER - BETTER
  88. */
Advertisement
Add Comment
Please, Sign In to add comment