3006

I generated two matrices of1000 x1000:

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

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

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?


As suggested in the comments, printing onlySystem.out.print("#"); takes7.8871 seconds, whereasSystem.out.print("B"); givesstill printing....

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

Test Conditions:

  • I ran this test fromNetbeans 7.2, with the output into its console
  • I usedSystem.nanoTime() for measurements
Dmitriy Popov's user avatar
Dmitriy Popov
2,3703 gold badges29 silver badges40 bronze badges
askedFeb 21, 2014 at 23:45
Kuba Spatny's user avatar
9
  • 67
    Try changing rand.nextInt(4) == 0 to i < 250 to eliminate the effect of the random generator. You might run out of entropy that slows down the random generationCommentedFeb 21, 2014 at 23:49
  • 3
    Both seem to run for same amount of time on my machine, ~4 seconds.CommentedFeb 21, 2014 at 23:51
  • 173
    if you are suggesting that printing B takes more time than printing #....why dont you try to print all B & all # rather than relying on random variable rCommentedFeb 21, 2014 at 23:52
  • 22
    Based on the accepted answer, you apparently didn't try running it with output redirected to a file or /dev/null.CommentedFeb 23, 2014 at 3:21
  • 29
    @fejese, Random() is not a cryptographical rng and so doesn't use up the entropy pool.CommentedFeb 25, 2014 at 11:44

3 Answers3

4260

Pure speculation is that you're using a terminal that attempts to doword-wrapping rather than character-wrapping, and treatsB 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 theB, 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).

But that's pure speculation.

Sign up to request clarification or add additional context in comments.

7 Comments

Brilliant deduction. But we should generalize from this lesson, and always measure performance with output either eliminated, directed to /dev/null (NUL on Windows) or at least to a file. Displaying on any sort of Console is generally very expensive IO, and always distorts timings -- even if not as dramatically confusingly as this.
@BobKerns: Surely that would still have generated an appropriate question though. The problem remains that printing Bs takes longer and not printing them isn't really a solution so much as a trick to help debug the problem.
@MrLister:System.out.println doesn't do wordwrapping; the thing it was outputting to was doing word-wrapping (and blocking, soSystem.out.println had to wait).
@Chris -- actually, I'll argue that not printing them IS the solution, to the problem of getting accurate timings of the algorithm. Each time you print to a Console (of any sort), you're invoking all manner of external processing not related to what you're testing the performance of. That's a bug in your measurement procedure, pure and simple. On the other hand, if you view the problem not as measurement, but understanding the discrepancy, then yes, not printing is a debugging trick. It comes down to, which problem are you trying to solve?
@BobKerns Thanks for injecting some sanity into this thread! So many people don't seem to understand this. You need to be careful that you areonly measuring the thing you are trying to measure
|
259

I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8;I usedSystem.nanoTime() for measurements.

Eclipse:

I got thesame time on both cases - around1.564 seconds.

Netbeans:

  • Using "#":1.536 seconds
  • Using "B":44.164 seconds

So, it looks like Netbeans has a bad performance on print to console.

After more research, I realized that the problem isline-wrapping of the max buffer of Netbeans (it's not restricted toSystem.out.println command), demonstrated by this code:

    for (int i = 0; i < 1000; i++) {        long t1 = System.nanoTime();        System.out.print("BBB......BBB"); // <- contains 1000 "B"s        long t2 = System.nanoTime();        System.out.println(t2 - t1);        System.out.println("");    }

The time results are less than 1 millisecond every iteration exceptevery fifth iteration, when the time result is around 225 milliseconds. Something like (in nanoseconds):

BBB...31744BBB...31744BBB...31744BBB...31744BBB...226365807BBB...31744BBB...31744BBB...31744BBB...31744BBB...226365807...

And so on.

Summary:

  1. Eclipse works perfectly with "B"
  2. Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).
Dmitriy Popov's user avatar
Dmitriy Popov
2,3703 gold badges29 silver badges40 bronze badges
answeredApr 3, 2015 at 15:01
Roy Shmuli's user avatar

3 Comments

can you elaborate on your research strategies and then what finally led you to find out that line-wrapping was the culprit? (i'm curious about your detective skills, that is!)
Word wrapping in Netbeans can be disabled.
"I used System.nanoTime()" ... generally speaking, microbenchmarking without a purpose built benchmarking harness is meaningless.
21

Yes, the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # =6.03 seconds
  2. Second Matrix: O and B =50.97 seconds

Looking at your code closely: you have used a line break at the end of the first loop. But you didn't use any line breaks in the 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 only5.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 only8.56 seconds and7.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("");                }

Another advice is to change the settings of NetBeans IDE. First of all, go to NetBeansTools and clickOptions. After that, clickEditor and go to theFormatting tab. Then selectAnywhere inLine Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings

Dmitriy Popov's user avatar
Dmitriy Popov
2,3703 gold badges29 silver badges40 bronze badges
answeredSep 5, 2019 at 5:25
Abdul Alim Shakir's user avatar

1 Comment

"It will take almost 6.24% less time to compile the program." surely you refer to executing, not compiling...
Protected question. To answer this question, you need to have at least 10 reputation on this site (not counting theassociation bonus). The reputation requirement helps protect this question from spam and non-answer activity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.