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

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

    Also We can use StopWatch class of Apache commons for measuring the time.

    Sample code

    org.apache.commons.lang.time.StopWatch sw = new org.apache.commons.lang.time.StopWatch();
    
    System.out.println("getEventFilterTreeData :: Start Time : " + sw.getTime());
    sw.start();
    
    // Method execution code
    
    sw.stop();
    System.out.println("getEventFilterTreeData :: End Time : " + sw.getTime());
    
    0 讨论(0)
  • 2020-11-21 11:46

    Use a profiler (JProfiler, Netbeans Profiler, Visual VM, Eclipse Profiler, etc). You'll get the most accurate results and is the least intrusive. They use the built-in JVM mechanism for profiling which can also give you extra information like stack traces, execution paths, and more comprehensive results if necessary.

    When using a fully integrated profiler, it's faily trivial to profile a method. Right click, Profiler -> Add to Root Methods. Then run the profiler just like you were doing a test run or debugger.

    0 讨论(0)
  • 2020-11-21 11:46

    This probably isn't what you wanted me to say, but this is a good use of AOP. Whip an proxy interceptor around your method, and do the timing in there.

    The what, why and how of AOP is rather beyond the scope of this answer, sadly, but that's how I'd likely do it.

    Edit: Here's a link to Spring AOP to get you started, if you're keen. This is the most accessible implementation of AOP that Iive come across for java.

    Also, given everyone else's very simple suggestions, I should add that AOP is for when you don't want stuff like timing to invade your code. But in many cases, that sort of simple and easy approach is fine.

    0 讨论(0)
  • 2020-11-21 11:46

    There are a couple of ways to do that. I normally fall back to just using something like this:

    long start = System.currentTimeMillis();
    // ... do something ...
    long end = System.currentTimeMillis();
    

    or the same thing with System.nanoTime();

    For something more on the benchmarking side of things there seems also to be this one: http://jetm.void.fm/ Never tried it though.

    0 讨论(0)
  • 2020-11-21 11:46

    In Java 8 a new class named Instant is introduced. As per doc:

    Instant represents the start of a nanosecond on the time line. This class is useful for generating a time stamp to represent machine time. The range of an instant requires the storage of a number larger than a long. To achieve this, the class stores a long representing epoch-seconds and an int representing nanosecond-of-second, which will always be between 0 and 999,999,999. The epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z where instants after the epoch have positive values, and earlier instants have negative values. For both the epoch-second and nanosecond parts, a larger value is always later on the time-line than a smaller value.

    This can be used as:

    Instant start = Instant.now();
    try {
        Thread.sleep(7000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Instant end = Instant.now();
    System.out.println(Duration.between(start, end));
    

    It prints PT7.001S.

    0 讨论(0)
  • 2020-11-21 11:47

    Gathered all possible ways together into one place.

    Date

    Date startDate = Calendar.getInstance().getTime();
    long d_StartTime = new Date().getTime();
    Thread.sleep(1000 * 4);
    Date endDate = Calendar.getInstance().getTime();
    long d_endTime = new Date().getTime();
    System.out.format("StartDate : %s, EndDate : %s \n", startDate, endDate);
    System.out.format("Milli = %s, ( D_Start : %s, D_End : %s ) \n", (d_endTime - d_StartTime),d_StartTime, d_endTime);
    

    System.currentTimeMillis()

    long startTime = System.currentTimeMillis();
    Thread.sleep(1000 * 4);
    long endTime = System.currentTimeMillis();
    long duration = (endTime - startTime);  
    System.out.format("Milli = %s, ( S_Start : %s, S_End : %s ) \n", duration, startTime, endTime );
    System.out.println("Human-Readable format : "+millisToShortDHMS( duration ) );
    

    Human Readable Format

    public static String millisToShortDHMS(long duration) {
        String res = "";    // java.util.concurrent.TimeUnit;
        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));
        long millis     = TimeUnit.MILLISECONDS.toMillis(duration) - 
                          TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(duration));
    
        if (days == 0)      res = String.format("%02d:%02d:%02d.%04d", hours, minutes, seconds, millis);
        else                res = String.format("%dd %02d:%02d:%02d.%04d", days, hours, minutes, seconds, millis);
        return res;
    }
    

    Guava: Google StopwatchJAR « An object of Stopwatch is to measures elapsed time in nanoseconds.

    com.google.common.base.Stopwatch g_SW = Stopwatch.createUnstarted();
    g_SW.start();
    Thread.sleep(1000 * 4);
    g_SW.stop();
    System.out.println("Google StopWatch  : "+g_SW);
    

    Apache Commons LangJAR « StopWatch provides a convenient API for timings.

    org.apache.commons.lang3.time.StopWatch sw = new StopWatch();
    sw.start();     
    Thread.sleep(1000 * 4);     
    sw.stop();
    System.out.println("Apache StopWatch  : "+ millisToShortDHMS(sw.getTime()) );
    

    JODA-TIME

    public static void jodaTime() throws InterruptedException, ParseException{
        java.text.SimpleDateFormat ms_SDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
        String start = ms_SDF.format( new Date() ); // java.util.Date
    
        Thread.sleep(10000);
    
        String end = ms_SDF.format( new Date() );       
        System.out.println("Start:"+start+"\t Stop:"+end);
    
        Date date_1 = ms_SDF.parse(start);
        Date date_2 = ms_SDF.parse(end);        
        Interval interval = new org.joda.time.Interval( date_1.getTime(), date_2.getTime() );
        Period period = interval.toPeriod(); //org.joda.time.Period
    
        System.out.format("%dY/%dM/%dD, %02d:%02d:%02d.%04d \n", 
            period.getYears(), period.getMonths(), period.getDays(),
            period.getHours(), period.getMinutes(), period.getSeconds(), period.getMillis());
    }
    

    Java date time API from Java 8 « A Duration object represents a period of time between two Instant objects.

    Instant start = java.time.Instant.now();
        Thread.sleep(1000);
    Instant end = java.time.Instant.now();
    Duration between = java.time.Duration.between(start, end);
    System.out.println( between ); // PT1.001S
    System.out.format("%dD, %02d:%02d:%02d.%04d \n", between.toDays(),
            between.toHours(), between.toMinutes(), between.getSeconds(), between.toMillis()); // 0D, 00:00:01.1001 
    

    Spring Framework provides StopWatch utility class to measure elapsed time in Java.

    StopWatch sw = new org.springframework.util.StopWatch();
    sw.start("Method-1"); // Start a named task
        Thread.sleep(500);
    sw.stop();
    
    sw.start("Method-2");
        Thread.sleep(300);
    sw.stop();
    
    sw.start("Method-3");
        Thread.sleep(200);
    sw.stop();
    
    System.out.println("Total time in milliseconds for all tasks :\n"+sw.getTotalTimeMillis());
    System.out.println("Table describing all tasks performed :\n"+sw.prettyPrint());
    
    System.out.format("Time taken by the last task : [%s]:[%d]", 
            sw.getLastTaskName(),sw.getLastTaskTimeMillis());
    
    System.out.println("\n Array of the data for tasks performed « Task Name: Time Taken");
    TaskInfo[] listofTasks = sw.getTaskInfo();
    for (TaskInfo task : listofTasks) {
        System.out.format("[%s]:[%d]\n", 
                task.getTaskName(), task.getTimeMillis());
    }
    

    OutPut:

    Total time in milliseconds for all tasks :
    999
    Table describing all tasks performed :
    StopWatch '': running time (millis) = 999
    -----------------------------------------
    ms     %     Task name
    -----------------------------------------
    00500  050%  Method-1
    00299  030%  Method-2
    00200  020%  Method-3
    
    Time taken by the last task : [Method-3]:[200]
     Array of the data for tasks performed « Task Name: Time Taken
    [Method-1]:[500]
    [Method-2]:[299]
    [Method-3]:[200]
    
    0 讨论(0)
提交回复
热议问题