How do I time a method's execution in Java?

前端 未结 30 3195
北荒
北荒 2020-11-21 11:15
  1. How do I get a method\'s execution time?
  2. Is there a Timer utility class for things like timing how long a task takes, etc?

Mos

30条回答
  •  没有蜡笔的小新
    2020-11-21 11:55

    Just a small twist, if you don't use tooling and want to time methods with low execution time: execute it many times, each time doubling the number of times it is executed until you reach a second, or so. Thus, the time of the Call to System.nanoTime and so forth, nor the accuracy of System.nanoTime does affect the result much.

        int runs = 0, runsPerRound = 10;
        long begin = System.nanoTime(), end;
        do {
            for (int i=0; i end - begin);
        System.out.println("Time for timedMethod() is " + 
            0.000000001 * (end-begin) / runs + " seconds");
    

    Of course, the caveats about using the wall clock apply: influences of JIT-compilation, multiple threads / processes etc. Thus, you need to first execute the method a lot of times first, such that the JIT compiler does its work, and then repeat this test multiple times and take the lowest execution time.

提交回复
热议问题