使用 JMH 做 Kotlin 的基准测试

2024-01-08 22:58
文章标签 使用 测试 kotlin 基准 jmh

本文主要是介绍使用 JMH 做 Kotlin 的基准测试,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

640?wx_fmt=jpeg

一. 基准测试

基准测试是指通过设计科学的测试方法、测试工具和测试系统,实现对一类测试对象的某项性能指标进行定量的和可对比的测试。

基准测试是一种测量和评估软件性能指标的活动。你可以在某个时候通过基准测试建立一个已知的性能水平(称为基准线),当系统的软硬件环境发生变化之后再进行一次基准测试以确定那些变化对性能的影响。

二. JMH

JMH(Java Microbenchmark Harness) 是专门用于进行代码的微基准测试的一套工具API,也支持基于JVM的语言例如 Scala、Groovy、Kotlin。它是由 OpenJDK/Oracle 里面那群开发了 Java 编译器的大牛们所开发的工具。

三. 举例

首先,在 build.gradle 中添加 JMH 所需的依赖

 
  1. plugins {

  2.    id 'java'

  3.    id 'org.jetbrains.kotlin.jvm' version '1.3.10'

  4.    id "org.jetbrains.kotlin.kapt" version "1.3.10"

  5. }


  6. ...


  7. dependencies {

  8.    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

  9.    compile "org.jetbrains.kotlin:kotlin-reflect:1.3.10"

  10.    testCompile group: 'junit', name: 'junit', version: '4.12'


  11.    compile "org.openjdk.jmh:jmh-core:1.21"

  12.    kapt "org.openjdk.jmh:jmh-generator-annprocess:1.21"

  13.    ......

  14. }

3.1 对比 Sequence 和 List

在 Kotlin 1.2.70 的 release note 上曾说明:

使用 Sequence 有助于避免不必要的临时分配开销,并且可以显着提高复杂处理 PipeLines 的性能。

所以,有必要下面编写一个例子来证实这个说法:

 
  1. import org.openjdk.jmh.annotations.*

  2. import org.openjdk.jmh.results.format.ResultFormatType

  3. import org.openjdk.jmh.runner.Runner

  4. import org.openjdk.jmh.runner.options.OptionsBuilder

  5. import java.util.concurrent.TimeUnit


  6. /**

  7. * Created by tony on 2018-12-10.

  8. */

  9. @BenchmarkMode(Mode.Throughput) // 基准测试的模式,采用整体吞吐量的模式

  10. @Warmup(iterations = 3) // 预热次数

  11. @Measurement(iterations = 10, time = 5, timeUnit = TimeUnit.SECONDS) // 测试参数,iterations = 10 表示进行10轮测试

  12. @Threads(8) // 每个进程中的测试线程数

  13. @Fork(2)  // 进行 fork 的次数,表示 JMH 会 fork 出两个进程来进行测试

  14. @OutputTimeUnit(TimeUnit.MILLISECONDS) // 基准测试结果的时间类型

  15. open class SequenceBenchmark {


  16.    @Benchmark

  17.    fun testSequence():Int {


  18.        return sequenceOf(1,2,3,4,5,6,7,8,9,10)

  19.                .map{ it * 2 }

  20.                .filter { it % 3  == 0 }

  21.                .map{ it+1 }

  22.                .sum()

  23.    }


  24.    @Benchmark

  25.    fun testList():Int {


  26.        return listOf(1,2,3,4,5,6,7,8,9,10)

  27.                .map{ it * 2 }

  28.                .filter { it % 3  == 0 }

  29.                .map{ it+1 }

  30.                .sum()

  31.    }

  32. }


  33. fun main() {


  34.    val options = OptionsBuilder()

  35.            .include(SequenceBenchmark::class.java.simpleName)

  36.            .output("benchmark_sequence.log")

  37.            .build()

  38.    Runner(options).run()

  39. }

在运行上述代码之前,需要先执行 ./gradlew build

然后,再运行main函数,得到如下的结果。

 
  1. # Run complete. Total time: 00:05:23


  2. REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on

  3. why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial

  4. experiments, perform baseline and negative tests that provide experimental control, make sure

  5. the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.

  6. Do not assume the numbers tell you what you want them to tell.


  7. Benchmark                        Mode  Cnt      Score     Error   Units

  8. SequenceBenchmark.testList      thrpt   20  15924.272 ± 305.825  ops/ms

  9. SequenceBenchmark.testSequence  thrpt   20  23099.938 ± 515.524  ops/ms

果然,经过多次链式调用时 Sequence 比起 List 具有更高的效率。

如果把结果导出成json格式,还可以借助 jmh 相关的 gradle 插件生成可视化的报告。

 
  1. fun main() {


  2.    val options = OptionsBuilder()

  3.            .include(SequenceBenchmark::class.java.simpleName)

  4.            .resultFormat(ResultFormatType.JSON)

  5.            .result("benchmark_sequence.json")

  6.            .output("benchmark_sequence.log")

  7.            .build()

  8.    Runner(options).run()

  9. }

需要依赖到这个插件:https://github.com/jzillmann/gradle-jmh-report

借助 gradle-jmh-report 生成如下的报告:

640?wx_fmt=png

3.2 内联函数和非内联函数

Kotlin 的内联函数从编译器角度将函数的函数体复制到调用处实现内联,减少了使用高阶函数带来的隐性成本。

尝试编写一个例子:

 
  1. @BenchmarkMode(Mode.Throughput) // 基准测试的模式,采用整体吞吐量的模式

  2. @Warmup(iterations = 3) // 预热次数

  3. @Measurement(iterations = 10, time = 5, timeUnit = TimeUnit.SECONDS) // 测试参数,iterations = 10 表示进行10轮测试

  4. @Threads(8) // 每个进程中的测试线程数

  5. @Fork(2)  // 进行 fork 的次数,表示 JMH 会 fork 出两个进程来进行测试

  6. @OutputTimeUnit(TimeUnit.MILLISECONDS) // 基准测试结果的时间类型

  7. open class InlineBenchmark {


  8.    fun nonInlined(block: () -> Unit) { // 不用内联的函数

  9.        block()

  10.    }


  11.    inline fun inlined(block: () -> Unit) { // 使用内联的函数

  12.        block()

  13.    }


  14.    @Benchmark

  15.    fun testNonInlined() {


  16.        nonInlined {

  17.            println("")

  18.        }

  19.    }


  20.    @Benchmark

  21.    fun testInlined() {


  22.        inlined {

  23.            println("")

  24.        }

  25.    }


  26. }

得到如下的结果。

 
  1. # Run complete. Total time: 00:05:23


  2. REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on

  3. why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial

  4. experiments, perform baseline and negative tests that provide experimental control, make sure

  5. the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.

  6. Do not assume the numbers tell you what you want them to tell.


  7. Benchmark                        Mode  Cnt   Score   Error   Units

  8. InlineBenchmark.testInlined     thrpt   20  95.866 ± 4.085  ops/ms

  9. InlineBenchmark.testNonInlined  thrpt   20  92.736 ± 3.085  ops/ms

果然,内联更高效一些。

640?wx_fmt=png

3.3 协程和RxJava

自从 Kotlin 有协程这个功能之后,经常会有人提起协程和RxJava的比对。

于是,我也尝试编写一个例子,此例子使用的 Kotlin 1.3.10 ,协程的版本1.0.1,RxJava 2.2.4

 
  1. @BenchmarkMode(Mode.Throughput) // 基准测试的模式,采用整体吞吐量的模式

  2. @Warmup(iterations = 3) // 预热次数

  3. @Measurement(iterations = 10, time = 5, timeUnit = TimeUnit.SECONDS) // 测试参数,iterations = 10 表示进行10轮测试

  4. @Threads(8) // 每个进程中的测试线程数

  5. @Fork(2)  // 进行 fork 的次数,表示 JMH 会 fork 出两个进程来进行测试

  6. @OutputTimeUnit(TimeUnit.MILLISECONDS) // 基准测试结果的时间类型

  7. @State(Scope.Thread) // 为每个线程独享

  8. open class CoroutinesBenchmark {


  9.    var counter1 = AtomicInteger()

  10.    var counter2 = AtomicInteger()


  11.    @Setup

  12.    fun prepare() {


  13.        counter1.set(0)

  14.        counter2.set(0)

  15.    }


  16.    fun calculate(counter:AtomicInteger): Double {


  17.        val result = ArrayList<Int>()


  18.        for (i in 0 until 10_000) {


  19.            result.add(counter.incrementAndGet())

  20.        }


  21.        return result.asSequence().filter { it % 3 ==0 }.map { it *2 + 1 }.average()

  22.    }


  23.    @Benchmark

  24.    fun testCoroutines() = runBlocking {


  25.        calculate(counter1)

  26.    }


  27.    @Benchmark

  28.    fun testRxJava() = Observable.fromCallable { calculate(counter2) }.blockingFirst()


  29. }

执行结果如下:

 
  1. # Run complete. Total time: 00:05:23


  2. REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on

  3. why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial

  4. experiments, perform baseline and negative tests that provide experimental control, make sure

  5. the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.

  6. Do not assume the numbers tell you what you want them to tell.


  7. Benchmark                            Mode  Cnt   Score   Error   Units

  8. CoroutinesBenchmark.testCoroutines  thrpt   20  17.719 ± 2.249  ops/ms

  9. CoroutinesBenchmark.testRxJava      thrpt   20  18.151 ± 0.429  ops/ms

此基准测试采用的是 Throughput 模式,得分越高则性能越好。从得分来看,两者差距不大。(对于两者的比较,我还没有做更多的测试。)

640?wx_fmt=png

总结

基准测试有很多典型的应用场景,例如想比较某些方法的执行时间,对比接口不同实现在相同条件下的吞吐量等等。在这些场景下,使用 JMH 都是很不错的选择。

关注【Java与Android技术栈】

更多精彩内容请关注扫码

640?wx_fmt=jpeg


这篇关于使用 JMH 做 Kotlin 的基准测试的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/585126

相关文章

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图