Java - Calculate time taken for the code to execute in milliseconds or nanoseconds


If you want to know how much time did your program took to execute a program or code then you can make use of the following methods from the System class.

  1. System.currentTimeMillis()
  2. System.nanoTime()
Example 1: Calculate the time taken to execute code in Milliseconds
import java.util.ArrayList;
import java.util.List;

public class Example {

    public static void main(String... args) {

       long timeMilli1 = System.currentTimeMillis();
       myFunc();
       long timeMilli2 = System.currentTimeMillis();

       System.out.println("Time taken for the code to execute: " + (timeMilli2 - timeMilli1) + " milliseconds");


    }

    public static void myFunc() {
        List mylist= new ArrayList<>();
        for(int i=0;i<=1000;i++) {
            mylist.add("Hello! :"+i);
        }
    }

}
Output:
Time taken for the code to execute: 19 milliseconds


Example 2: Calculate the time taken to execute code in nanoseconds
import java.util.ArrayList;
import java.util.List;

public class Example {

    public static void main(String... args) {

       long timeNano1 = System.nanoTime();
       myFunc();
       long timeNano2 = System.nanoTime();

       System.out.println("Time taken for the code to execute: " + (timeNano2 - timeNano1) + " nanoseconds");


    }

    public static void myFunc() {
        List mylist= new ArrayList<>();
        for(int i=0;i<=1000;i++) {
            mylist.add("Hello! :"+i);
        }
    }

}
Output:
Time taken for the code to execute: 19247334 milliseconds



Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.