richi_urb
richi_urb

Reputation: 9

The problem with using System.nanoTime() for calculating the working time of the method

I want to know the working time of some methods in my study project by Java tools. When I tried to use System.nanoTime(), I had noticed, that comparison of the working time of two methods looks a litle bit strange. The first and the second methods should work for the same time, but I got another result in console - the working time distinguished in several times.

Whether calculating time by System.nanoTime() function gives different efficiency results on the simple code:

String a = "a";
String b = "b";
String c = "c";
String d = "d";

HashMap<String, String> stringMap = new HashMap<>();
stringMap.put(a, "map_a");
stringMap.put(b, "map_b");

HashMap<String, String> secondStringMap = new HashMap<>();
secondStringMap.put(c, "map_c");
secondStringMap.put(d, "map_d");

String[] firstArray = new String[2];
String[] secondArray = new String[2];

long startTime = System.nanoTime();

firstArray[0] = stringMap.get(a);
secondArray[1] = stringMap.get(b);

long midTime = System.nanoTime();

firstArray[0] = secondStringMap.get(c);
secondArray[1] = secondStringMap.get(d);

long endTime = System.nanoTime();

System.out.println(midTime - startTime);
System.out.println(endTime - midTime);

And I got a very interesting result - the first part worked for approximately 5-10 times slower than the second.

So the question is:

Why does calculating working time with System.nanoTime() give different result for the first and the second part of the code? Is there any better way to count time?

Upvotes: 0

Views: 27

Answers (0)

Related Questions