测量Java方法的执行时间。通用方法?

时间:2018-07-08 10:40:08

标签: java benchmarking microbenchmark

对于较大的JAVA项目,我想测量不同类的许多不同方法的执行时间。这些方法大多数都调用某些API,因此,我认为How do I time a method's execution in Java?的经典方法应该可以解决问题(使用分析器几乎没有带来什么好处?)。因为我认为将每个方法调用包装在某种样板代码中并不是真正的“干净代码”(也不是非常面向对象的),所以我想出了以下使用lambda表达式来度量方法执行时间的通用方法。我现在的问题是:这是个好主意吗?或更准确地说:由于我是一名JAVA专家,因此我的代码中是否有任何棘手的部分可能会弄乱我的结果(除了通常的JIT魔术之外)?

    import java.util.concurrent.Callable;

    public class MethodExecutionTimer {

        private long executionTime;

        public MethodExecutionTimer() {
            this.executionTime = 0;
        }

        public <T> T timeFunction(Callable<T> methodToTime) throws Exception {
            long startTime = System.nanoTime();
            T result = methodToTime.call();
            long endTime = System.nanoTime();
            this.executionTime = (endTime - startTime);
            return result;
        }

 public long getExecutionTimeInSeconds() {return this.executionTime / 1000000000;}
    }

一个简单的测试可能看起来像这样:

public class MethodExecutionTimerTest {

private int fib(int n) {
    if (n <= 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    } else {
        return fib(n - 1) + fib(n - 2);
    }
}

public void testWithFib() {
        try {
        MethodExecutionTimer timer = new MethodExecutionTimer();
        Callable<Integer> theFunctionToTime = () -> fib(46);
        Integer fibResult = timer.timeFunction(theFunctionToTime);
        long executionTime = timer.getExecutionTimeInSeconds();

        System.out.println("Calculated: " + fibResult + " in " + executionTime + " seconds.");
        } catch (Exception e) {
            System.out.println("Error");
        }
    }

0 个答案:

没有答案
相关问题