How to time a method in Java?

To time a method in Java, call System.nanoTime() before, then after.

Here's how you do it:

long before = System.nanoTime();
// call the method here <----
long after = System.nanoTime();

long timeNanoSeconds = after - before;
long timeMilliSeconds = timeNanoSeconds / 1_000_000;

System.out.println("Method worked for " + timeMilliSeconds + "ms (" + timeNanoSeconds + "ns)");