为什么打印“B"比打印“#"慢得多? [英] Why is printing "B" dramatically slower than printing "#"?

查看:40
本文介绍了为什么打印“B"比打印“#"慢得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成了两个 1000 x 1000 的矩阵:

I generated two matrices of 1000 x 1000:

第一个矩阵:O#.
第二个矩阵:OB.

First Matrix: O and #.
Second Matrix: O and B.

使用以下代码,完成第一个矩阵需要 8.52 秒:

Using the following code, the first matrix took 8.52 seconds to complete:

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("");
 }

使用此代码,完成第二个矩阵需要 259.152 秒:

With this code, the second matrix took 259.152 seconds to complete:

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("");
}

运行时间截然不同的原因是什么?

What is the reason behind the dramatically different run times?

正如评论中所建议的,仅打印 System.out.print("#"); 需要 7.8871 秒,而 System.out.print("B"); 给出 仍在打印....

As suggested in the comments, printing only System.out.print("#"); takes 7.8871 seconds, whereas System.out.print("B"); gives still printing....

作为其他人指出它通常适用于他们,我尝试了 Ideone.com 例如,以及两个部分代码以相同的速度执行.

As others who pointed out that it works for them normally, I tried Ideone.com for instance, and both pieces of code execute at the same speed.

测试条件:

  • 我从 Netbeans 7.2 运行了这个测试,输出到它的控制台
  • 我使用 System.nanoTime() 进行测量
  • I ran this test from Netbeans 7.2, with the output into its console
  • I used System.nanoTime() for measurements

推荐答案

纯推测是您使用的终端尝试执行word-wrapping 而不是字符换行,并将 B 视为单词字符,而将 # 视为一个非单词字符.因此,当它到达一行的末尾并搜索换行的位置时,它几乎立即看到一个 # 并且很高兴地在那里换行;而对于 B,它必须继续搜索更长的时间,并且可能有更多的文本要换行(这在某些终端上可能很昂贵,例如,输出退格,然后输出空格以覆盖被换行的字母).

Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B as a word character but # as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a # almost immediately and happily breaks there; whereas with the B, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).

但这纯粹是猜测.

这篇关于为什么打印“B"比打印“#"慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆