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
Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap