使用JMH进行简单的微基准测试 [英] Simple micro-benchmark with JMH

查看:102
本文介绍了使用JMH进行简单的微基准测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个有关堆栈溢出的问题的启发,我编写了一个微型基准检查,什么更有效:

Inspired by another question on Stack Overflow, I have written a micro-benchmark to check, what is more efficient:

  • 有条件地检查零除或
  • 捕获并处理ArithmeticException

下面是我的代码:

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark {

    private int a = 10;
    // a little bit less obvious than int b = 0;
    private int b = (int) Math.floor(Math.random());

    @Benchmark
    public float conditional() {
        if (b == 0) {
            return 0;
        } else {
            return a / b;
        }
    }

    @Benchmark
    public float exceptional() {
        try {
            return a / b;
        } catch (ArithmeticException aex) {
            return 0;
        }
    }
}

我对JMH完全陌生,不确定代码是否正确.

I am totally new to JMH and not sure if the code is allright.

我的基准测试正确吗?你看到任何错误吗?

Is my benchmark correct? Do you see any mistakes?

不建议:请勿建议在 https://codereview.stackexchange.com 上提问.对于Codereview,代码必须已经按预期工作.我不确定该基准测试是否按预期工作.

Side not: please don't suggest asking on https://codereview.stackexchange.com. For Codereview code must already work as intended. I am not sure this benchmark works as intended.

推荐答案

我看到的最大的不足是任何形式的随机性.这将使分支预测更容易进行工作,这将使这两种方法都比实际除以0的方法更快.

The big thing I see missing is any sort of randomness. That will make it easier for the branch prediction to do its work, which will make both methods faster than they probably would be in practice for division by 0.

我将对每种方法进行三种变化:

I would do three variations of each method:

  1. 具有零位混合的随机数组,并使用该数组的索引对基准进行参数化.
  2. 具有非零数字的随机数组
  3. 全为0

这应该使您对整体性能有一个很好的了解,包括分支预测.对于点(1),以0s与非0s的比率进行游戏也可能很有趣.

That should give you a good idea of the overall performance, including branch prediction. For point (1), it may also be interesting to play with the ratio of 0s to non-0s.

我忘记了JMH是否允许您直接在数组的各个值上进行参数化.如果是这样,那么我会使用它.否则,您将必须在该数组的索引上进行参数化.在那种情况下,我还要将全0放在一个数组中,以便保持访问是所有测试的一部分.我可能还会创建一个控件",该控件仅访问数组并返回其值,以便您可以更直接地找出该开销.

I forget if JMH lets you parameterize directly on individual values of an array. If it does, then I'd use that. Otherwise, you'll have to parameterize on the index to that array. In that case, I would also put the all-0s in an array so that the stay access is part of all tests. I would also probably create a "control" that just accesses the array and returns its value, so that you can find out that overhead more directly.

还有个小问题:我不认为您需要返回浮点数,因为它们只是从除法器实际产生的整数中转换而来.

Also, a minor nit: I don't think you need to return floats, since they'll just be converted from the ints that the division actually produces.

这篇关于使用JMH进行简单的微基准测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆