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

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

    Spring provides a utility class org.springframework.util.StopWatch, as per JavaDoc:

    Simple stop watch, allowing for timing of a number of tasks, exposing total running time and running time for each named task.

    Usage:

    StopWatch stopWatch = new StopWatch("Performance Test Result");
    
    stopWatch.start("Method 1");
    doSomething1();//method to test
    stopWatch.stop();
    
    stopWatch.start("Method 2");
    doSomething2();//method to test
    stopWatch.stop();
    
    System.out.println(stopWatch.prettyPrint());
    

    Output:

    StopWatch 'Performance Test Result': running time (millis) = 12829
    -----------------------------------------
    ms     %     Task name
    -----------------------------------------
    11907  036%  Method 1
    00922  064%  Method 2
    

    With Aspects:

    @Around("execution(* my.package..*.*(..))")
    public Object logTime(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object retVal = joinPoint.proceed();
        stopWatch.stop();
        log.info(" execution time: " + stopWatch.getTotalTimeMillis() + " ms");
        return retVal;
    }
    

提交回复
热议问题