2015-01-01 3 views
0

메서드를 실행하고 완료하는 데 걸리는 시간을 측정하는 방법을 알고 있습니다. 그러나 10 가지 방법이 있고 각각 10 가지 방법이 실행되는 데 걸리는 시간을 측정하고 싶습니다. 내가 계속 System.currentTimeMillis() 번을 쓰는 것이 비효율적 일 것입니다.메서드를 실행하는 데 걸리는 시간을 측정하는 메서드를 만드는 방법

그래서이 문제에 대해보다 효율적인 방법이 있는지 궁금합니다. 즉, 특정 메서드를 실행하는 데 걸리는 시간을 측정하는 메서드를 만들고 해당 메서드가 매개 변수로 전달됩니다 (이것은 아이디어입니다 내 머리 꼭대기에 나는 이것에 관해 완전히 틀릴 수있다)?

long startTime = System.currentTimeMillis(); 
// Create graph and read file 
Graph dag = new Graph(); 
read_file(dag, "FILE.txt"); 
long endTime = System.currentTimeMillis(); 
System.out.println("Load file: " + (endTime - startTime) + " milliseconds"); 

// Transposing graph 
startTime = System.currentTimeMillis(); 
Graph dag_rev = new Graph(); 
Graph dag_transposed = dag_rev.transposed(dag); 
endTime = System.currentTimeMillis(); 
System.out.println("Transposing graph: " + (endTime - startTime) + " milliseconds"); 
+0

내가 아는 것에 따라 실행 시간을 측정하는 다른 방법이 없다. http://stackoverflow.com/questions/3382954/measure-execution-time-for-a-java-method에서 읽을 수 있습니다. –

답변

2

좋은 솔루션은, Aspect 지향적 인 프로그래밍을 사용하고 랩 일부 @Around (AspectJ를 주석)의 조언을 적용하는 것입니다 시간 계산을 사용하여 대상 메서드를 실행합니다. Spring provides a simple implementation with AspectJ.

또 다른 해결책은

public static <T> T time(Callable<T> code) throws Exception { // possibly add a String message parameter to print out 
    long startTime = System.currentTimeMillis(); 
    T value = code.call(); // or wrap unchecked exception 
    long endTime = System.currentTimeMillis(); 
    System.out.println("Method executed: " + (endTime - startTime) + " milliseconds"); 
    return value; 
} 

같은 방법을 제공 그리고 이것은 (이 방법

Graph graph = time(() -> { 
    Graph dag = new Graph(); 
    read_file(dag, "FILE.txt"); 
    return dag; 
}); 

Callable로, 당신의 메서드 호출을 포함 당신이 실행하려는 코드를 전달하는 것입니다 AOP가 당신을 위해 할 것 인 것의 거의 단순화.)