简体   繁体   中英

Why is execution times measured differently here using Java?

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:

在此处输入图像描述

Code 2: 在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM