How to measure the time taken by a function in Java?

Java Programming Java 8Object Oriented Programming

java.lang.System.currentTimeMillis() method can be used to compute the time taken by a function in java. Trick is simple. Get the before time and after time using currentTimeMillis() where before time is the time when method is invoked and after time is when method has executed. See the example below −


 Live Demo

public class Tester{
   public static void main(String[] args) {
      long startTime = System.currentTimeMillis();
      long endTime = System.currentTimeMillis();
      System.out.println("Time taken: " + (endTime -startTime) + " ms");

   private static void longRunningMethod() {
      try {
      } catch (InterruptedException e) {


Time taken: 1000 ms
Published on 30-Aug-2018 08:19:18