How to find time taken to run a Java program?

后端 未结 7 1978
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 06:17

I have a Java application that I\'ve been working on and I just realized that the program has to return a value in less than a minute, but don\'t know how to find or display

7条回答
  •  没有蜡笔的小新
    2020-12-24 06:41

    If you have Spring as a dependency of your project (or don't mind adding it), you can use StopWatch. As the name suggests, once initialized it will count the time until you stop it. You can then check the time taken for a task. Multiple StopWatches can be used simultaneously to multiple tasks keeping the code clean.

    Besides keeping your code clean, StopWatches help with formatting the time and other utility methods.

    public void myMethod(){
        StopWatch stopWatch = new StopWatch();
    
        stopWatch.start("Task1");
        // ...
        // Do my thing
        // ...
        stopWatch.stop();
        System.out.println("Task executed in " + stopWatch.getTotalTimeSeconds() + "s");
    }
    

提交回复
热议问题