Kub*_*tny 2662 java performance loops for-loop system.out
我生成了两个1000
x 矩阵1000
:
第一矩阵:O
和#
.
第二个矩阵:O
和B
.
使用以下代码,第一个矩阵需要8.52秒才能完成:
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("#");
}
}
System.out.println("");
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,第二个矩阵需要259.152秒才能完成:
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B"); //only line changed
}
}
System.out.println("");
}
Run Code Online (Sandbox Code Playgroud)
运行时间大不相同的原因是什么?
正如评论中所建议的那样,打印只System.out.print("#");
需要7.8871
几秒钟,而System.out.print("B");
给出still printing...
.
正如其他人指出它通常适用于他们一样,我尝试过Ideone.com,两段代码都以相同的速度执行.
测试条件:
System.nanoTime()
测量T.J*_*der 3994
纯粹的推测是你正在使用一个试图进行自动换行而不是字符换行的终端,并将其视为B
一个单词字符,而不是#
一个非单词字符.因此,当它到达一条线的末端并寻找一条断线的地方时,它#
几乎立刻就会看到并在那里快乐地打破; 而对于它B
,它必须继续搜索更长的时间,并且可能有更多的文本要包装(在某些终端上可能很昂贵,例如,输出退格,然后输出空格来覆盖被包装的字母).
但那是纯粹的猜测.
Roy*_*uli 194
我在Eclipse vs Netbeans 8.0.2上进行了测试,两者都使用Java版本1.8; 我用于System.nanoTime()
测量.
我在两种情况下都得到了相同的时间 - 大约1.564秒.
因此,看起来Netbeans在打印到控制台时表现不佳.
经过更多的研究,我意识到问题是Netbeans的最大缓冲区的换行(它不限于System.out.println
命令),由此代码演示:
for (int i = 0; i < 1000; i++) {
long t1 = System.nanoTime();
System.out.print("BBB......BBB"); \\<-contain 1000 "B"
long t2 = System.nanoTime();
System.out.println(t2-t1);
System.out.println("");
}
Run Code Online (Sandbox Code Playgroud)
每次迭代时间结果小于1毫秒,除了每第五次迭代,当时间结果大约为225毫秒.像(以纳秒为单位)的东西:
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.
Run Code Online (Sandbox Code Playgroud)
等等..
Abd*_*kir 16
Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.
Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B");
}
if(j%100==0){ //Adding a line break in second loop
System.out.println();
}
}
System.out.println("");
}
Run Code Online (Sandbox Code Playgroud)
Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.
归档时间: |
|
查看次数: |
230165 次 |
最近记录: |