How to use JMH with gradle?

后端 未结 5 1816
清歌不尽
清歌不尽 2021-02-04 02:33

I want to use JMH, an OpenJDK microbenchmark tool, with gradle. However, Im getting the NPE on compilation. On the other hand, JMH works when using from maven.<

5条回答
  •  长发绾君心
    2021-02-04 03:03

    My bad, I was trying to benchmark a method that has an argument - of course JMH will not know what to pass :) Once when I created a void method with no arguments, everything worked.

    My build.gradle:

    defaultTasks 'build'
    
    apply plugin: 'java'
    apply plugin: 'shadow'
    
    buildscript {
        repositories {
            mavenCentral()
            maven {
                name 'Shadow'
                url 'http://dl.bintray.com/content/johnrengelman/gradle-plugins'
            }
        }
        dependencies {
            classpath 'org.gradle.plugins:shadow:0.7.4'
        }
    }
    
    jar {
        manifest {
            attributes 'Main-Class': 'org.openjdk.jmh.Main'
        }
    }
    
    repositories {
        mavenCentral()
    }
    
    
    build.doLast {
        tasks.shadow.execute()
    }
    
    shadow {
        outputFile = new File('build/libs/microbenchmarks.jar')
    }
    
    ext {
        lib = [
            ... other dependencies...
            jmh:            'org.openjdk.jmh:jmh-core:0.2'
        ]
    }
    
    dependencies {
        compile lib... other dependencies...
        compile lib.jmh
    }
    
    sourceCompatibility = 1.7
    

    Build tests and jar:

    gw clean build
    

    and then run them with:

    java -jar build/libs/microbenchmarks.jar ".*" -wi 2 -i 10 -f 2 -t 16
    

    UPDATE

    From recent versions of JMH, you would also need to add dependency to:

    org.openjdk.jmh:jmh-generator-annprocess:0.5.4
    

    and you can use shadow 0.8.

提交回复
热议问题