开发者

Java - Big result difference when benchmarking an algorithm in ms and ns

I was performing some test performance on an algorithm and noticed something weird. Maybe I am missing something here.

I first measure the time in milliseconde:

long startTime = System.currentTimeMillis();
x.sort(sortStringInput);
long endTime = System.currentTimeMillis();

and then in nanoseconde:

long startTime = 开发者_Python百科System.nanoTime();
x.sort(sortStringInput);
long endTime = System.nanoTime();

The results are 437ms qnd 26366ns.

I am calling the same method so how can it be possible to get a result in ns which is way smaller than the one in ms. I know that 1 ms is 1 000 000 ns so 26366 is even smaller than 1 ms...

Thanks,


Are you sorting the same list twice? The second call will be extremely fast if the list is already sorted.


Depending on what platform you're on, System.nanoTime() itself can be very slow. You're better off running your benchmark multiple times and measuring the overall duration in miliseconds.


I suggest you run the test for at least 2 seconds before counting any result and run the test for at least 2 seconds and take the average. The following code prints.

Average sort time 116 ms.
Average sort time 117100526 ns.
Average sort time 116 ms.
Average sort time 116530255 ns.
Average sort time 117 ms.
Average sort time 116905977 ns.

Code

public static void main(String... args) throws IOException {
    String[] strings = new String[100 * 1000];
    for (int i = 0; i < strings.length; i++)
        strings[i] = "" + Math.random();

    int runTimeMS = 2000;
    for (int i = 0; i <= 3; i++) {
        {
            long start = System.currentTimeMillis();
            int count = 0;
            do {
                Arrays.sort(strings.clone());
                count++;
            } while (System.currentTimeMillis() - start < runTimeMS);
            long time = System.currentTimeMillis() - start;
            if (i>0) System.out.println("Average sort time " + time / count + " ms.");
        }
        {
            long start = System.nanoTime();
            int count = 0;
            do {
                Arrays.sort(strings.clone());
                count++;
            } while (System.nanoTime() - start < runTimeMS * 1000L * 1000L);
            long time = System.nanoTime() - start;
            if (i>0) System.out.println("Average sort time " + time / count + " ns.");
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜