作者:banli | 来源:互联网 | 2024-11-26 17:12
引言:在软件开发过程中,了解程序的执行效率是非常重要的。本文将通过一个具体的例子,介绍如何利用Java来计算一段代码的执行时间,这对于性能调优和问题排查具有重要意义。
public class ProgramDuration {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date start = new Date();
System.out.println("程序开始时间: " + formatter.format(start));
performOperations();
Date end = new Date();
System.out.println("程序结束时间: " + formatter.format(end));
printDuration(start, end);
}
private static void performOperations() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void printDuration(Date start, Date end) {
long difference = end.getTime() - start.getTime();
long secOndsInMilli= 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = difference / daysInMilli;
difference = difference % daysInMilli;
long elapsedHours = difference / hoursInMilli;
difference = difference % hoursInMilli;
long elapsedMinutes = difference / minutesInMilli;
difference = difference % minutesInMilli;
long elapsedSecOnds= difference / secondsInMilli;
System.out.printf("程序运行了 %d 天, %d 小时, %d 分钟, %d 秒", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}
}