System.currentTimeMillis()
method. Here's a simple example :public class ExecutionTimeExample {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
// Call the method you want to measure
myMethod();
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.println("Execution time in milliseconds: " + executionTime);
}
public static void myMethod() {
// Code of the method to be measured
for (int i = 0; i < 1000000000; i++) {
// Do nothing
}
}
}
Execution time in milliseconds: 4
System.currentTimeMillis()
method is called twice - once at the beginning of the main()
method to record the start time, and once after the method you want to measure (myMethod()
in this case) has finished executing to record the end time. The difference between these two times is the execution time of the method.System.nanoTime()
instead of System.currentTimeMillis()
.