通常可以通过 long ms=System.currentTimeMillis(); 的方式来取得以毫秒为单位起始时间和终止时间,它们的时间差除以一千就知道一段Java程序运行了多少秒,但多少秒并不直观,比如900秒你要反应一下,说15分就马上反应过来了。下面提供了具体示例代码:
public class Test {
public static void main(String[] args) {
long startMs = System.currentTimeMillis();
for(int i = 0; i < 1000; i+=2){
System.out.println(i);
}
long endMs = System.currentTimeMillis();
System.out.println("Time elapsed:" + ms2DHMS(startMs,endMs));
}
private static String ms2DHMS(long startMs,long endMs){
String retval = null;
long secondCount = (endMs - startMs) / 1000;
String ms = (endMs - startMs) % 1000 + "ms";
long days = secondCount / (60 * 60 * 24);
long hours = (secondCount % (60 * 60 * 24)) / (60 * 60);
long minutes = (secondCount % (60 * 60)) / 60;
long seconds = secondCount % 60;
if (days > 0) {
retval = days + "d" + hours + "h" + minutes + "m" + seconds + "s";
} else if (hours > 0) {
retval = hours + "h" + minutes + "m" + seconds + "s";
} else if (minutes > 0) {
retval = minutes + "m" + seconds + "s";
} else if(seconds > 0) {
retval = seconds + "s";
}else {
return ms;
}
return retval + ms;
}
}
结果:
'''
998
Time elapsed:6ms