首页
随机
最近更改
特殊页面
社群首页
参数设置
关于WHY42
免责声明
WHY42
搜索
用户菜单
登录
欢迎来到Riguz的小站!这是一个私人wiki,用来记录一些我的笔记。
查看“︁JMH Benchmark”︁的源代码
←
JMH Benchmark
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
JMH是一个测试Java程序性能的工具,比如我们现在要测试一下JDK8自带的Base64和[http://www.java2s.com/Code/Java/Development-Class/AfastandmemoryefficientclasstoencodeanddecodetoandfromBASE64infullaccordancewithRFC2045.htm 另一个实现]的性能。 先看看 build.gradle 中怎么写: <syntaxhighlight lang="groovy"> group 'riguz' version '1.0-SNAPSHOT' apply plugin: 'java' sourceCompatibility = 1.8 sourceSets { jmh } repositories { mavenCentral() } dependencies { jmhCompile project jmhCompile 'org.openjdk.jmh:jmh-core:1.21' jmhCompile 'org.openjdk.jmh:jmh-generator-annprocess:1.21' jmhCompile group: 'junit', name: 'junit', version: '4.12' testCompile group: 'junit', name: 'junit', version: '4.12' } task jmh(type: JavaExec, description: 'Executing JMH benchmarks') { classpath = sourceSets.jmh.runtimeClasspath main = 'org.openjdk.jmh.Main' } </syntaxhighlight> 然后写一个类: <syntaxhighlight lang="java"> @Benchmark @Warmup(iterations = 1, time = 5) @Measurement(iterations = 1, time = 5) public void encodeWithJdk() { final byte[] bytes = Dream.text.getBytes(); byte[] encoded = Base64.getEncoder().encode(bytes); byte[] decoded = Base64.getDecoder().decode(encoded); assertTrue(Arrays.equals(bytes, decoded)); } @Benchmark @Warmup(iterations = 1, time = 5) @Measurement(iterations = 1, time = 5) public void encodeWithBase64Codec() throws IOException { final byte[] bytes = Dream.text.getBytes(); byte[] encoded = Base64Codec.encodeToByte(bytes, true); byte[] decoded = Base64Codec.decodeFast(encoded, encoded.length); assertTrue(Arrays.equals(bytes, decoded)); } </syntaxhighlight> 其中Dream.text是一个很长的字符串。执行gradle的jmh task之后,可以得到结果 <pre> Benchmark Mode Cnt Score Error Units Base64BenchMark.encodeWithBase64Codec thrpt 5 15.296 ± 2.538 ops/s Base64BenchMark.encodeWithJdk thrpt 5 13.029 ± 1.563 ops/s </pre> 看样子要比JDK的实现强一丢丢,当然只是在上面的这种情况之下。差距并不大。 参考: * http://tutorials.jenkov.com/java-performance/jmh.html#why-are-java-microbenchmarks-hard * https://www.jianshu.com/p/192b782c31bc [[Category:Java]]
返回
JMH Benchmark
。