0

The following sequence has to be printed.

  12345
  2345
  345
  45
  5
  This can be done using one loops or two loops, but surprisingly when I use two loops, it takes a lot more time.

Here is what I have done. One loop way:

//Prints are commented so that outputs are easily visible
public void generateSequence1(int num){
        long timeStarted = System.currentTimeMillis();
        for(int j = 1, i= 1; i<=num && j<= num; ){
            i++;
//            System.out.print(i++);
            if(i==num+1){
                i = ++j;
//                System.out.println();
            }

        }
        System.out.println("Using 1 loop, time taken: " + (System.currentTimeMillis() - timeStarted));
    }

Here is the Two loop way

public void generateSequencePlainWay(int num){
        long timeStarted = System.currentTimeMillis();
        for(int i = 1; i<= num; i++){
            for(int j = i;j <= num; j++){
//                System.out.print(j);
            }
//            System.out.println();
        }
        System.out.println("Using 2 loop, time taken: " + (System.currentTimeMillis() - timeStarted));
    }

Now when I call the methods

TestConducts tc = new TestConducts();
        tc.generateSequencePlainWay(50000);
        tc.generateSequence1(50000);

The output is as follows.(I fluctuates a bit each time, but almost the same)

Using 2 loop, time taken: 668

Using 1 loop, time taken: 7

Both these methods have n*(n-1)/2 operations. Then why such a huge time difference? Am I doing something wrong? Or this is the way it should be?And which way is better?

Community
  • 1
  • 1
Debanjan
  • 2,817
  • 2
  • 24
  • 43
  • 1
    micro benchmarks with Java are never a good idea because the JIT compiler gets in the way. – hardillb Jan 07 '17 at 17:22
  • Please suggest another way of benchmarking. – Debanjan Jan 07 '17 at 17:30
  • Also, the commented out code doing the actual work is definitely a big problem. The JIT can detect that nothing is happening in the second method and if you run it a couple of times, it'll be executed in 0 seconds; essentially, it understood it is effectively a no-op. Please refer to the linked question to do a proper benchmark. The numbers you have are entirely meaningless. – Tunaki Jan 07 '17 at 17:34
  • Also, first loop does 37507500 comparisons while second loop does 12507500 comparisons when int num is 5000; – Pallav Jha Jan 07 '17 at 17:36

0 Answers0