Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package jmhmath;
- import org.openjdk.jmh.annotations.*;
- import org.openjdk.jmh.infra.Blackhole;
- import org.openjdk.jmh.runner.Runner;
- import org.openjdk.jmh.runner.RunnerException;
- import org.openjdk.jmh.runner.options.Options;
- import org.openjdk.jmh.runner.options.OptionsBuilder;
- import java.io.IOException;
- import java.math.BigDecimal;
- import java.math.MathContext;
- import java.util.Locale;
- import java.util.Random;
- import java.util.concurrent.TimeUnit;
- @Fork(value = 0, warmups = 0)
- @OutputTimeUnit(TimeUnit.NANOSECONDS)
- @BenchmarkMode(Mode.AverageTime)
- @State(Scope.Benchmark)
- public class BigDecimalBenchmark {
- private Blackhole blackhole;
- private Random random;
- @Setup(Level.Trial)
- public void init(Blackhole blackhole){
- this.blackhole = blackhole;
- this.random = new Random();
- }
- @Benchmark
- public void testDoubleMath(){
- double d = (random.nextDouble()+random.nextDouble())/20;
- blackhole.consume(d);
- }
- @Benchmark
- public void testBigDecimalMath(){
- BigDecimal d = (BigDecimal.valueOf(random.nextDouble()).add(BigDecimal.valueOf(random.nextDouble()))).divide(BigDecimal.valueOf(20));
- blackhole.consume(d);
- }
- @Benchmark
- public void testBigDecimalMathWithEval(){
- double d = (BigDecimal.valueOf(random.nextDouble()).add(BigDecimal.valueOf(random.nextDouble()))).divide(BigDecimal.valueOf(20)).doubleValue();
- blackhole.consume(d);
- }
- @Benchmark
- public void testQuadruple(){
- double d = new Quadruple(random.nextDouble()).add(random.nextDouble()).divide(20).doubleValue();
- blackhole.consume(d);
- }
- private void run(String... args) throws IOException, RunnerException {
- Locale.setDefault(Locale.US);
- final Options opt = new OptionsBuilder()
- .include(BigDecimalBenchmark.class.getSimpleName())
- .forks(1)
- .build();
- new Runner(opt).run();
- }
- public static void main(String... args) throws IOException, RunnerException {
- new BigDecimalBenchmark().run(args);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement