温馨提示×

java怎么显示程序运行时间

小亿
85
2024-05-15 18:36:17
栏目: 编程语言

在Java中,可以使用System.currentTimeMillis()或者System.nanoTime()来获取程序运行时间。以下是两种方法的示例代码:

  1. 使用System.currentTimeMillis():
long startTime = System.currentTimeMillis();
// your code here
long endTime = System.currentTimeMillis();

long duration = endTime - startTime;
System.out.println("Program execution time: " + duration + " milliseconds");
  1. 使用System.nanoTime():
long startTime = System.nanoTime();
// your code here
long endTime = System.nanoTime();

long duration = (endTime - startTime) / 1000000; // 转换为毫秒
System.out.println("Program execution time: " + duration + " milliseconds");

请注意,System.nanoTime()提供了更高精度的计时,但在一些系统上可能受到CPU频率调整和系统定时器的影响。因此,在某些情况下,使用System.currentTimeMillis()可能更为稳定。

0