在Java中,可以使用System.currentTimeMillis()或者System.nanoTime()来获取程序运行时间。以下是两种方法的示例代码:
使用System.currentTimeMillis():long startTime = System.currentTimeMillis();// your code herelong endTime = System.currentTimeMillis();long duration = endTime - startTime;System.out.println("Program execution time: " + duration + " milliseconds");使用System.nanoTime():long startTime = System.nanoTime();// your code herelong endTime = System.nanoTime();long duration = (endTime - startTime) / 1000000; // 转换为毫秒System.out.println("Program execution time: " + duration + " milliseconds");请注意,System.nanoTime()提供了更高精度的计时,但在一些系统上可能受到CPU频率调整和系统定时器的影响。因此,在某些情况下,使用System.currentTimeMillis()可能更为稳定。


