How do I time a method's execution in Java?

前端 未结 30 2743
北荒
北荒 2020-11-21 11:15
  1. How do I get a method\'s execution time?
  2. Is there a Timer utility class for things like timing how long a task takes, etc?

Mos

30条回答
  •  伪装坚强ぢ
    2020-11-21 11:42

    Come on guys! Nobody mentioned the Guava way to do that (which is arguably awesome):

    import com.google.common.base.Stopwatch;
    
    Stopwatch timer = Stopwatch.createStarted();
    //method invocation
    LOG.info("Method took: " + timer.stop());
    

    The nice thing is that Stopwatch.toString() does a good job of selecting time units for the measurement. I.e. if the value is small, it'll output 38 ns, if it's long, it'll show 5m 3s

    Even nicer:

    Stopwatch timer = Stopwatch.createUnstarted();
    for (...) {
       timer.start();
       methodToTrackTimeFor();
       timer.stop();
       methodNotToTrackTimeFor();
    }
    LOG.info("Method took: " + timer);
    

    Note: Google Guava requires Java 1.6+

提交回复
热议问题