How to find time taken to run a Java program?

后端 未结 7 1927
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 06:17

I have a Java application that I\'ve been working on and I just realized that the program has to return a value in less than a minute, but don\'t know how to find or display

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 06:56

    This is a typical usecase for aspects, for example using Spring AOP:

    @Aspect
    public class TimerAspect {
    
        private static final Logger LOG = Logger.getLogger(TimerAspect.class);
    
        @Around("com.xyz.myapp.MyClass.myMethod()")
        public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
            long startTime = System.nanoTime();
            Object retVal = pjp.proceed();
            long endTime = System.nanoTime();
            LOG.info(String.format("Call to %s.%s with args %s took %s ns", pjp.getTarget(), pjp.getSignature(), Arrays.toString(pjp.getArgs()), endTime - startTime));
            return retVal;
        }
    }
    

    And in your application context:

    
       
    

提交回复
热议问题