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

前端 未结 30 2734
北荒
北荒 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:41

    Really good code.

    http://www.rgagnon.com/javadetails/java-0585.html

    import java.util.concurrent.TimeUnit;
    
    long startTime = System.currentTimeMillis();
    ........
    ........
    ........
    long finishTime = System.currentTimeMillis();
    
    String diff = millisToShortDHMS(finishTime - startTime);
    
    
      /**
       * converts time (in milliseconds) to human-readable format
       *  "hh:mm:ss"
       */
      public static String millisToShortDHMS(long duration) {
        String res = "";
        long days  = TimeUnit.MILLISECONDS.toDays(duration);
        long hours = TimeUnit.MILLISECONDS.toHours(duration)
                       - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
        long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
                         - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
        long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
                       - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
        if (days == 0) {
          res = String.format("%02d:%02d:%02d", hours, minutes, seconds);
        }
        else {
          res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
        }
        return res;
      }
    

提交回复
热议问题