What is the most elegant way to track the execution times on how long a task took in a gradle build script? In an optimal case log the time directly same or next line to the tas
Just to elaborate on Peter Niederwieser's answer: We wanted to do the same thing, as well as a report timings at the end of the build, so slow steps are obvious (and appropriate parties feel a small but healthy bit of shame when they slow down the build!).
BUILD SUCCESSFUL
Total time: 1 mins 37.973 secs
Task timings:
579ms :myproject-foo:clean
15184ms :myproject-bar:clean
2839ms :myproject-bar:compileJava
10157ms :myproject-bar:jar
456ms :myproject-foo:compileJava
391ms :myproject-foo:libs
101ms :myproject-foo:jar
316ms :myproject-bar:compileTestJava
364ms :myproject-foo:compileTestJava
53353ms :myproject-foo:test
2146ms :myproject-bar:test
8348ms :www/node:npmInstall
687ms :www/node:npmTest
Something like the code below can be dropped into your top level build.gradle
to report timings during execution, or after completion.
// Log timings per task.
class TimingsListener implements TaskExecutionListener, BuildListener {
private Clock clock
private timings = []
@Override
void beforeExecute(Task task) {
clock = new org.gradle.util.Clock()
}
@Override
void afterExecute(Task task, TaskState taskState) {
def ms = clock.timeInMs
timings.add([ms, task.path])
task.project.logger.warn "${task.path} took ${ms}ms"
}
@Override
void buildFinished(BuildResult result) {
println "Task timings:"
for (timing in timings) {
if (timing[0] >= 50) {
printf "%7sms %s\n", timing
}
}
}
@Override
void buildStarted(Gradle gradle) {}
@Override
void projectsEvaluated(Gradle gradle) {}
@Override
void projectsLoaded(Gradle gradle) {}
@Override
void settingsEvaluated(Settings settings) {}
}
gradle.addListener new TimingsListener()