我知道如何衡量方法执行和完成所需的时间。但是,如果我有 10 种不同的方法,并且我想测量这 10 种方法中的每一种方法的运行时间,该怎么办?一直写 20 次 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");
最佳答案
AOP,使用注解。您只需要使用 System.currentTimeMills() 但它确保您只编写一次并根据需要多次使用它。 这是 Spring AOP 的示例: http://www.mkyong.com/spring/spring-aop-examples-advice/ 没有 Spring : http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html
关于java - 如何创建一个方法来测量执行一个方法所花费的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27732580/