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.
- System.currentTimeMillis()
- System.nanoTime()
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
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!