JMH基准迭代中的随机峰值

时间:2019-06-12 13:17:33

标签: java garbage-collection microbenchmark jmh

我正在尝试采用一种非常快速的方法(〜20 us / op),它似乎工作得很好,除了一些随机很长的迭代:

Iteration  63: 14.319 us/op
Iteration  64: 13.128 us/op
Iteration  65: 15.198 us/op
Iteration  66: 20.822 us/op
Iteration  67: 21.669 us/op
Iteration  68: 21.439 us/op
Iteration  69: 15.946 us/op
Iteration  70: 18.793 us/op
Iteration  71: 19.212 us/op
Iteration  72: 816.129 us/op  // oopsy
Iteration  73: 22.115 us/op
Iteration  74: 15.143 us/op
Iteration  75: 18.423 us/op
Iteration  76: 15.238 us/op

Result "benchmark.StuffBench.run_bench":
  20.629 ±(99.9%) 9.164 us/op [Average]
  (min, avg, max) = (12.689, 20.629, 816.129), stdev = 47.763
  CI (99.9%): [11.464, 29.793] (assumes normal distribution)

可能是GC,但是shouldDoGc(false)并没有任何改变:

final Options options = new OptionsBuilder()
                .include(StuffBench.class.getSimpleName())
                .shouldDoGC(false)
                .build();
Collection<RunResult> runResults = new Runner(options).run();

基准类:

@Fork(value = 2)
@Threads(1)
@Warmup(iterations = 1000, time = 50, timeUnit = TimeUnit.MICROSECONDS)
@Measurement(iterations = 150, time = 50, timeUnit = TimeUnit.MICROSECONDS)
@Timeout(time = 50, timeUnit = TimeUnit.MICROSECONDS)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@BenchmarkMode(Mode.AverageTime)
@State(Scope.Benchmark)
public class StuffBench {
    private Stuff stuff;

    @Setup
    public void initialize() {
        stuff = new Stuff();
    }

    @Benchmark
    public void run_bench() {
        stuff.run();
    }
}

1 个答案:

答案 0 :(得分:0)

为解决此类问题,我使用了所谓的抖动采样器。您有一个线程设置时间戳,运行代码,重置时间戳并暂停以不使CPU过载。第二个线程对时间戳进行采样,如果时间戳处于活动状态并且时间过长,例如20 us,您将打印出堆栈正在执行的操作。例如Thread.getStackTrace()结合最常见的堆栈跟踪,您就有一个可以指向问题的安全点(或问题之后的第一个安全点),这比科学还多了;;