I saw on the Internet that I was supposed to use System.nanoTime() but that doesn\'t work for me - it gives me the time with milliseconds precision. I just need
Such a benchmark that relies on short time-interval gives you unreliable results. You will always get different results, because of external factors like I/O, Swapping, Process Switches, Caches, Garbage Collection etc. Additionally the JVM optimizes your calls, so it's likely that the first measured things are going slower than later call. The JVM starts more and more to optimize the commands you execute.
Additionally the method like System.nanoTime() is dependent on the timers of the underlying system. They may (and most likely will) not have the granularity to measure in that accuracy. To cite the API:
This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change.
To really measure with high precision you need to access an external timing hardware with guaranteed precision.
To make your benchmark more stable you need to execute it more than once and to measure bigger time-intervals than only milliseconds.