0
public static void main(String[] args){
    int[] nums;
    int n = 1000000;
    int m = 1000;       
    List<Long> results = new ArrayList<Long>();
    Instant before, after;
    long delta;

    // for(int i = 0; i < 5; i++){
    //     nums = IntStream.rangeClosed(1, n).toArray();
    //     shuffle(nums);
    //     before = Instant.now(); 
    //     findKthSmallest(nums, m);
    //     quickSort(nums,0 , m-1);    
    //     after = Instant.now();
    //     delta = Duration.between(before, after).toMillis();
    //     System.out.println(delta);
    // }

    nums = IntStream.rangeClosed(1, n).toArray();
    shuffle(nums);
    before = Instant.now(); 
    findKthSmallest(nums, m);
    quickSort(nums,0 , m-1);    
    after = Instant.now();
    delta = Duration.between(before, after).toMillis();
    System.out.println(delta);
}

In the main method, I tried to print out delta 5 times. When I did it inside the loop (commented-out block), the delta decreased over time, which is weird. When I did it outside the loop (run the code 5 times), the deltas seem to be consistent. Why is this happening and how can I fix it? Thank you.

ndang6
  • 3
  • 3
  • What values are you getting for your delta? How much is it increasing by in the loop? – matt Apr 07 '20 at 13:35
  • 3
    Take a look: https://stackoverflow.com/questions/36198278/why-does-the-jvm-require-warmup – PM 77-1 Apr 07 '20 at 13:40
  • 1
    Use [JMH](https://openjdk.java.net/projects/code-tools/jmh/) for this kinds of tests. – Johannes Kuhn Apr 07 '20 at 14:11
  • @matt 15, 19, 29, 27, 23 for outside the loop. 20,8,9,13,10 for inside the loop – ndang6 Apr 07 '20 at 14:58
  • @ndang6 How much is the value decreasing when you use a loop. If it is taking 15 to 30 ms to run your application without the loop, I somehow doubt you're seeing jvm warmup time differences. – matt Apr 07 '20 at 15:02

1 Answers1

0

When you compile your java code, it compiles to java bytecode. When your program runs, it interprets the bytecode into machine code. Most parts of the code only run once, so the JVM only interprets it once and doesn't store the machine code. When the JVM notices you're running the same code over and over again, it compiles that section down to machine code and tries to optimize as well as it can. This is called Just-in-time compilation.

You can disable this, and force the program to constantly run interpreted with the JIT compiler disabled using the command line argument -nojit. This will lead to worse, but more consistent performance.

As for accurately measuring the warmed-up performance of a program, I suggest you identify how long it takes for the JVM to warm up and start measuring then.

Dejke
  • 168
  • 1
  • 9