Using Gradle, how can I print how long each task t

2019-04-14 10:12发布

问题:

Right now, for one of the gradle targets run frequently, the output looks like this:

:DataPlanner:clean
:common:clean
:server:clean
:simulator:clean
:util:clean
:util:compileJava
:util:processResources UP-TO-DATE
:util:classes
:util:compileTestJava
:util:processTestResources
:util:testClasses
:util:test
:util:jar
:common:compileJava
:common:processResources UP-TO-DATE
:common:classes
:common:compileTestJava
:common:processTestResources

How do I get it to look something more like this?

:DataPlanner:clean
took 2secs
:common:clean
took 2 secs
:server:clean
took 3 secs
:simulator:clean
took 4 secs
:util:clean
took 1 sec
...

If it's not possible to get every task to print its duration upon completion, printing the timestamp would be an acceptable alternative.

Any ideas?

Modifying one of the proposed solutions which didn't work for me, this one did:

gradle.taskGraph.beforeTask { Task task ->
task.ext.setProperty("startTime", new java.util.Date())
}

gradle.taskGraph.afterTask { Task task, TaskState state ->
    int secs = ( new java.util.Date().getTime() - task.ext.startTime.getTime() ) / 1000
    int mins = secs / 60

    if ( 4 < secs ) {
        int sec = secs - mins * 60
        println " -> took " + mins + ( ( 1 == mins ) ? " min " : " mins " ) + sec + ( ( 1 == sec ) ? " sec" : " secs" )
    }
}

回答1:

You could add pre and post execution hooks to do this. Before task execution add the current time as a property on the task, and then after execution you can compare the current time to the saved time.

import java.time.*
gradle.taskGraph.beforeTask { Task task ->
    task.ext.setProperty("startTime", Instant.now())
}

gradle.taskGraph.afterTask { Task task, TaskState state ->
    println task.name + " took " + Duration.between(task.ext.startTime, Instant.now()).toSeconds() + " seconds"
}

results in output like this:

$gradle clean
:clean
clean took 0.043000000 seconds


回答2:

I don't know how you got this specific output. However, you can use the --profile command line flag in order to get a report about your build. Then you'll get an html report located under build/reports/profile which in Gradle 2.3 looks like:

You can read more about it in Gradle documentation here.

If you insist on getting the specific output you specified you can try using the beforeTask and afterTask taskGraph hooks to measure the time and print it out. Just note that you'll need to be cautious about it in case gradle will be executed in parallel mode.



标签: gradle