Here I have this method

@Override public double calculateMiddleVarOfAxisZ(double axisZ) { long startTime = System.currentTimeMillis(); long current = System.currentTimeMillis(); countAxisZTimes++; countAxisZSum += axisZ; mapAxisZ.put(current, axisZ); if (mapAxisZ.size() == 1) { return axisZ; } Iterator iterator = mapAxisZ.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Long, Double> point = (Map.Entry) iterator.next(); long pointTime = point.getKey(); long difference = current - pointTime; if (difference > getTime(mapAxisZ)) { double val = point.getValue(); countAxisZTimes--; countAxisZSum -= val; iterator.remove(); } } double result = countAxisZSum / countAxisZTimes; Logger.logGeneral(String.valueOf(result) + " size : " + mapAxisZ.size()); long finishTime = System.currentTimeMillis(); Logger.logGeneral("Start : " + startTime + " finish : " + finishTime + " Time diff Z: " + ( finishTime - startTime)); return result; } 

I need to calculate the exact execution time. In my example, I take the time when the method started execution and when it finishes and find the difference

In the last line I display the log

 Start : 1481102600075 finish : 1481102600075 Time diff Z: 0 

As far as I understand, the minimum time unit available from this number is 1481102600075 this is a thousandth of a second (millisecond) 10 to 3 degrees. Since 1000 is a second.

So how in my case can be calculated more accurately? Maybe microseconds or nano ...

    3 answers 3

    You can get the current time in nanoseconds: System.nanoTime()
    Javadoc: https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--

      I do not advise using System.nanoTime() in my dimensions. The documentation for this method says:

      This method is not always possible, but it is not necessary.

      Those. values ​​may not be accurate at all.

      There are too many nuances in measuring performance, and with the current approach your values ​​will not be accurate. I recommend, for such purposes, to use the jmh framework.

      As a last resort, you can call the method N times, and then the total execution time divided by N + do not forget about the warm-up iterations.

      • hmm ... interesting. But you need to deal with the framework, but now I’ll try to count the number of iterations and time - Aleksey Timoshchenko

      Hugo library may come up. As indicated in the description of its repository, it is a means of logging a call to annotated functions.

      • Have you tried to add this library to your project? I can not. I did everything as it is written on your link, but still it does not output anything to the log ... - Aleksey Timoshchenko
      • Yes, I used this library, but I searched for the logs by these symbols - "⇢" and "⇠" - s_klepcha