Advertisement
Guest User

Untitled

a guest
Aug 7th, 2021
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. package jmhmath;
  2.  
  3. import org.openjdk.jmh.annotations.*;
  4. import org.openjdk.jmh.infra.Blackhole;
  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.io.IOException;
  11. import java.math.BigDecimal;
  12. import java.math.MathContext;
  13. import java.util.Locale;
  14. import java.util.Random;
  15. import java.util.concurrent.TimeUnit;
  16.  
  17. @Fork(value = 0, warmups = 0)
  18. @OutputTimeUnit(TimeUnit.NANOSECONDS)
  19. @BenchmarkMode(Mode.AverageTime)
  20. @State(Scope.Benchmark)
  21. public class BigDecimalBenchmark {
  22.  
  23.     private Blackhole blackhole;
  24.     private Random random;
  25.  
  26.     @Setup(Level.Trial)
  27.     public void init(Blackhole blackhole){
  28.         this.blackhole = blackhole;
  29.         this.random = new Random();
  30.     }
  31.  
  32.  
  33.     @Benchmark
  34.     public void testDoubleMath(){
  35.         double d = (random.nextDouble()+random.nextDouble())/20;
  36.         blackhole.consume(d);
  37.     }
  38.  
  39.  
  40.     @Benchmark
  41.     public void testBigDecimalMath(){
  42.         BigDecimal d = (BigDecimal.valueOf(random.nextDouble()).add(BigDecimal.valueOf(random.nextDouble()))).divide(BigDecimal.valueOf(20));
  43.         blackhole.consume(d);
  44.     }
  45.  
  46.     @Benchmark
  47.     public void testBigDecimalMathWithEval(){
  48.         double d = (BigDecimal.valueOf(random.nextDouble()).add(BigDecimal.valueOf(random.nextDouble()))).divide(BigDecimal.valueOf(20)).doubleValue();
  49.         blackhole.consume(d);
  50.     }
  51.  
  52.     @Benchmark
  53.     public void testQuadruple(){
  54.         double d = new Quadruple(random.nextDouble()).add(random.nextDouble()).divide(20).doubleValue();
  55.         blackhole.consume(d);
  56.     }
  57.  
  58.  
  59.     private void run(String... args) throws IOException, RunnerException {
  60.         Locale.setDefault(Locale.US);
  61.         final Options opt = new OptionsBuilder()
  62.                 .include(BigDecimalBenchmark.class.getSimpleName())
  63.                 .forks(1)
  64.                 .build();
  65.         new Runner(opt).run();
  66.     }
  67.  
  68.     public static void main(String... args) throws IOException, RunnerException {
  69.         new BigDecimalBenchmark().run(args);
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement