4
我已经从我的Java编程书中得到了一个简单的程序,只是添加了一点。System.out.print导致延迟?
package personal;
public class SpeedTest {
public static void main(String[] args) {
double DELAY = 5000;
long startTime = System.currentTimeMillis();
long endTime = (long)(startTime + DELAY);
long index = 0;
while (true) {
double x = Math.sqrt(index);
long now = System.currentTimeMillis();
if (now >= endTime) {
break;
}
index++;
}
System.out.println(index + " loops in " + (DELAY/1000) + " seconds.");
}
}
这将返回128478180 loops in 5.0 seconds.
如果我的if语句前加上System.out.println(x);
,然后我在5秒内循环次数下降到400,000,是由于System.out.println()
延迟?还是只是x
没有被计算,当我不打印出来?
打印到控制台必须是最差的事情,你可以做性能明智的。 IO操作需要很长时间。 – Tunaki
System.out.println是一个IO操作,是的,它可以影响任何程序的性能 – Sanjeev
好的问题,我不明白downvotes。仅仅因为这对你来说是微不足道的,并不意味着你应该倒下。 – Maroun