How to check the execution time of a method in Java?

In Java, you can use the System.currentTimeMillis() method to track the execution time of a method. The execution time can be obtained by recording the timestamps of when the method starts and ends, and then calculating the difference between the two timestamps.

Here is a simple example code:

public class Example {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        
        // 执行需要计算执行时间的方法
        myMethod();
        
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        
        System.out.println("方法执行时间:" + executionTime + " 毫秒");
    }
    
    public static void myMethod() {
        // 方法的具体实现
    }
}

In the example code above, the start time stamp startTime was recorded before calling the myMethod() method, and the end time stamp endTime was recorded after the method was executed. By calculating the difference between these two time stamps, the method’s execution time executionTime was obtained. Finally, by printing the output, we can see the method’s execution time.

It is important to note that the System.currentTimeMillis() method returns the current time in milliseconds, so the calculation results are also in milliseconds. For more precise time calculations, one can use the System.nanoTime() method, which returns the time in nanoseconds.

bannerAds