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

前端 未结 30 2769
北荒
北荒 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 12:03

    You can use Perf4j. Very cool utility. Usage is simple

    String watchTag = "target.SomeMethod";
    StopWatch stopWatch = new LoggingStopWatch(watchTag);
    Result result = null; // Result is a type of a return value of a method
    try {
        result = target.SomeMethod();
        stopWatch.stop(watchTag + ".success");
    } catch (Exception e) {
        stopWatch.stop(watchTag + ".fail", "Exception was " + e);
        throw e; 
    }
    

    More information can be found in Developer Guide

    Edit: Project seems dead

提交回复
热议问题