-2

What is the difference between these 2? They both give me the execution-times with slighlty different values and I can tell they are written differently. But since the outcome is nearly identical, what does code 2 do that code 1 does not? What actually is the function of "sum" and is it even executed?

Code 1:

for (int i = 0; i < 10; i++)
    {
    long n0 = System.nanoTime();
    long n1 = System.nanoTime();
    System.out.println(" resolution " + (n1 - n0) + " nanoseconds");
    }

Code 2:

int[] given = {1,2,3,4,5,6,7,8,9,0};
    int sum = 0;
    for (int i = 0; i < 10; i++)
    {
        long t0 = System.nanoTime();
        sum += given[i];
        long t1 = System.nanoTime();
        System.out.println(" resolution " + (t1 - t0) + " nanoseconds");
    }

Here is the output for those who asked:

Code 1:

enter image description here

Code 2: enter image description here

Dyson
  • 23
  • 6
  • One is calculating the sum of an array and the other one isn't? – Nexevis Aug 31 '22 at 12:53
  • Well, code 2 does a little bit more, as it sums up an array of integers. Can you share the times that you see? – marstran Aug 31 '22 at 12:53
  • Can you share the output? – Yohan Aug 31 '22 at 12:55
  • 2
    If *feels* like you're trying to write a microbenchmark (or some equivalent code). This is **very tricky** to get right and as good start you should [read this question](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). **tl;dr** use existing frameworks and don't try to build your own, you're almost guaranteed to get plenty of details wrong. – Joachim Sauer Aug 31 '22 at 12:57
  • 1
    Also, [please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) – Joachim Sauer Aug 31 '22 at 13:04

1 Answers1

1

It is simply code to try out System.nanoTime(). Doing something or nothing between two calls does not make a discernible difference. The resolution of the clock is about 100 ns.

As sum is not printed, the compiler might have optimized the code by removing just that extra code.

Furthermore it seems that nanoTime alone already requires ~100 ns.


Note The code is primarily written for ones own curiosity.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138