Java Microbenchmarking Harness vs System.getNanotime()

 xts2011188_706_120_582 发布于 2023-01-16 16:27

问题1:为什么JMH比简单更好System.getNanotime()

问题2:从结果(看看benchmarking results部分)我可以得出什么结果validateLongKeyBinary比64%更快validateLongKeyAscii

示例(代码):

import net.spy.memcached.util.StringUtils;
import org.openjdk.jmh.annotations.GenerateMicroBenchmark;

public class KeyBench {

private static final String LONG_KEY = "thisIsAFunkyKeyWith_underscores_AndAlso334" +
            "3252545345NumberslthisIsAFunkyKeyWith_underscores_AndAlso3343252545345Numbe" +
            "rslthisIsAFunkyKeyWith_underscores_AndAlso3343252545345NumberslthisIsAFunkyK" +
            "eyWith_underscores_AndAlso3343252545345Numbersl";


    @GenerateMicroBenchmark
    public void validateLongKeyBinary() {
        StringUtils.validateKey(LONG_KEY, true);
    }

    @GenerateMicroBenchmark
    public void validateLongKeyAscii() {
        StringUtils.validateKey(LONG_KEY, false);
    }
}

基准测试结果

# Running: benchmarks.KeyBench.validateLongKeyAscii

Result : 393,667 ±(95%) 13,985 ±(99%) 20,094 ops/ms
  Statistics: (min, avg, max) = (357,445, 393,667, 413,004), stdev = 19,552
  Confidence intervals: 95% [379,682, 407,653], 99% [373,573, 413,762]


# Running: benchmarks.KeyBench.validateLongKeyBinary

Result : 644,023 ±(95%) 6,881 ±(99%) 9,887 ops/ms
  Statistics: (min, avg, max) = (621,784, 644,023, 654,178), stdev = 9,620
  Confidence intervals: 95% [637,142, 650,904], 99% [634,136, 653,910]

Benchmark                             Mode Thr     Count  Sec         Mean   Mean error    Units
b.KeyBench.validateLongKeyAscii      thrpt   1        10    1      393,667       20,094   ops/ms
b.KeyBench.validateLongKeyBinary     thrpt   1        10    1      644,023        9,887   ops/ms

Aleksey Ship.. 14

JMH维护者在这里.

让我提出一个主要问题:如果您可以自己编写大部分内容,为什么要使用该库?答案实际上很简单:当然,您可以在无限时间内编写所有内容,但在实践中,我们必须重用代码以适应合理的时间.

现在,似乎只有两个代码周围的时间戳足以衡量其性能.但是,您必须控制您正在测量的是什么,例如,您是否仍处于过渡预热阶段,您的代码是否实际执行,或者您在优化后测量空心壳,您的效果在统计上有多重要等等.等等良好的基准框架试图帮助解决这个问题.

您可以通过查看JMH样本,我们的基准测试会话或相关的SO答案,一瞥您将面临的问题.哦,使用nanoTime比你想象的更难.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有