2016-11-24 24 views
0

有什麼方法可以計算包中每個方法所花費的時間(它不包含任何類)?而不是打包每個方法的開始時間和結束時間。還有其他的選擇嗎?包中每種方法的時間計算。

在此先感謝!

+1

你看過AOP嗎? –

+0

如果您只需要這樣一次,但並非永遠只需要看一次Java Profiler – Ralph

+0

,請查看關於分析應用程序的以下技巧:https://www.infoq.com/articles/java-profiling-with-open-來源/ –

回答

0

使用AspectJ您可以使用。圍繞()註釋:

@Aspect 
public class TimedAnnotation { 
    @Around("execution(* *(..)) && @annotation(TimedMethod)") 
    public Object around(ProceedingJoinPoint point) throws Throwable { 
     long start = System.currentTimeMillis(); 
     try { 

      Object p = point.proceed(); 

      return p; 
     } 
     finally { 
      System.out.println(System.currentTimeMillis() - start); 
     } 
    } 
} 

你還是得把這個註釋爲每個方法:

@TimedMethod 
public void doSomething() { 
... 
} 

而且你需要添加的AspectJ到您的pom.xml:

<dependency> 
     <groupId>org.aspectj</groupId> 
     <artifactId>aspectjrt</artifactId> 
     <version>1.7.3</version> 
    </dependency> 
    <dependency> 
     <groupId>org.aspectj</groupId> 
     <artifactId>aspectjweaver</artifactId> 
     <version>1.8.9</version> 
    </dependency> 
+0

它是否適用於此代碼:public void doSomething(){xyzclass.execute()}。我需要計算xyzclass中的doSomething和execute方法的時間。 – manikumar

+0

如果你控制xyzclass,你可以把@TimedMethod放在.execute()的地方。 –