Track execution time per task in gradle script?

后端 未结 8 2128
深忆病人
深忆病人 2021-01-30 06:37

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

8条回答
  •  失恋的感觉
    2021-01-30 07:22

    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()
    

提交回复
热议问题