Java Program Execution Time Calculation
In Java, you can use either System.currentTimeMillis() or System.nanoTime() method to calculate the running time of a program.
- Utilize the System.currentTimeMillis() method:
long startTime = System.currentTimeMillis();
// 程序运行代码
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("程序运行时间:" + totalTime + "毫秒");
- Using the System.nanoTime() method:
long startTime = System.nanoTime();
// 程序运行代码
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println("程序运行时间:" + totalTime + "纳秒");
Note: The System.nanoTime() method provides higher precision compared to the System.currentTimeMillis() method, but it is not suitable for calculating wall-clock time. Therefore, when calculating the running time of a program, it is recommended to use the System.currentTimeMillis() method.