简体   繁体   中英

How to create a method to measure the time it takes to execute a method

I know how to measure the time a method takes to execute and finish. But what if I have 10 different methods and I want to measure how much time each of the 10 methods take to run. It will be inefficient for me to keep writing System.currentTimeMillis() twenty times.

So I am just wondering is there a more efficient method to this problem, ie create a method that measure the time it takes for a particular method to run and that particular method will be passed as a parameter (This is an idea on top of my head and I can be completely wrong about this) ?

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");

AOP, use annotations. you need to use System.currentTimeMills() only but it make sure that you write it once and use it as many times as you want. Here is and example with Spring AOP : http://www.mkyong.com/spring/spring-aop-examples-advice/ Without Spring : http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html

A good solution, though possibly hard to set up, is to use Aspect Oriented Programming and apply some @Around (AspectJ annotation) advice that wraps the execution of the target method with the time calculation. Spring provides a simple implementation with AspectJ .

Another solution is to provide a method like

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;
}

And then pass the code you want executed, which includes your method call, as a Callable to this method

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

(This is pretty much a simplification of what AOP would do for you.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM