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

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

问题描述

我生成了两个矩阵 1000 x 1000

I generated two matrices of 1000 x 1000:

第一张矩阵: O

第二张矩阵: O 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

推荐答案

纯猜测是你正在使用的终端试图做自动换行而不是字符acter-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天全站免登陆