Skip to content

Instantly share code, notes, and snippets.

@mrbald
Last active February 27, 2024 16:39
Show Gist options
  • Save mrbald/7bbb5113c3164d5243314da8c28649a1 to your computer and use it in GitHub Desktop.
Save mrbald/7bbb5113c3164d5243314da8c28649a1 to your computer and use it in GitHub Desktop.
JMH gradle without plugin for multi-module projects
...
subprojects {
...
apply plugin: 'java'
apply plugin: 'scala'
sourceCompatibility = 1.8
targetCompatibility = 1.8
sourceSets.main {
java.srcDirs = ['src/main/java']
scala.srcDirs = ['src/main/scala']
scala.include '**/*.*'
}
sourceSets.test {
java.srcDirs = ['src/test/java']
scala.srcDirs = ['src/test/scala']
scala.include '**/*.*'
}
// https://docs.gradle.org/current/userguide/building_java_projects.html#sec:java_source_sets
sourceSets {
jmh {
java.srcDirs = ['src/jmh/java']
scala.srcDirs = ['src/jmh/scala']
resources.srcDirs = ['src/jmh/resources']
compileClasspath += sourceSets.main.runtimeClasspath
}
}
dependencies {
...
jmhImplementation 'org.openjdk.jmh:jmh-core:1.27'
jmhAnnotationProcessor 'org.openjdk.jmh:jmh-generator-annprocess:1.27'
}
// https://docs.gradle.org/current/dsl/org.gradle.api.tasks.JavaExec.html
task jmh(type: JavaExec, dependsOn: jmhClasses) {
main = 'org.openjdk.jmh.Main'
classpath = sourceSets.jmh.compileClasspath + sourceSets.jmh.runtimeClasspath
// To enable the built-in stacktrace sampling profiler
// args = ['-prof', 'stack']
}
// to make sure benchmarks always get compiled
classes.finalizedBy(jmhClasses)
}
...
@edumucelli
Copy link

Thanks, @CSchoel! I have had checked your post before and I was not able to make it work as I am not very used to the the Gradle scripting, converting it from Kotlin DSL was also not straightforward for me. However, giving a second try it worked! I have then completely dropped the JMH gradle plugin! Here is the commit. Really appreciated!

@kepocnhh
Copy link

kepocnhh commented Feb 1, 2023

I came across the fact that if you want to write benchmarks in Kotlin (not the code being checked, but the code of the benchmarks themselves), then annotationProcessor will not be enough. The code will be generated only by annotations in the Java code. Kotlin will be ignored. But you can use kapt instead, the code will be generated immediately and Java and Kotlin.

Here you can see an example where benchmarks are written immediately in both Kotlin and Java.

Actually an annotation processor is not required in case of JMH. JMH has a special org.openjdk.jmh.generators.bytecode.JmhBytecodeGenerator. Here you can see how to make a task in gradle that will generate code without using annotationProcessor and kapt. Not as the best solution, I want to share for those who may be useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment