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
Advertisements
Try Out Code2care Dev Tools:

Advertisements



Android Java Linux Microsoft Google Python macOS Notepad++ Microsoft Teams CSS PHP SharePoint Html Linux C Programs Bootstrap jQuery Sublime Android Studio Facebook Eclipse WhatsApp News MySQL Json HowTos JavaScript FTP S3


Advertisements


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, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency