Menu
Topics Index
...
`


Exploring java.lang > System >
Siva Nookala - 06 Oct 2016
The currentTimeMillis method returns the current time in terms of milliseconds since midnight, January 1, 1970. The currentTimeMillis method is to time how long various parts of your program take to execute .

Elapsed
import java.lang.*;

class Elapsed
{
    public static void main(String arg[])
    {
        long start, end;
        System.out.println("Timing a for loop from 0 to 1000");
        // time a for loop from o to 1000
        start = System.currentTimeMillis(); // get time
        System.out.println("Starting time in milliseconds : " + start);
        
        for (int i = 0; i < 1000; i++)  // LINE A
        {
            
            for(int j =0; j < 2000; j++)
            {
                for( int k =0; k < 3000; k++)
                {
                    
                }
            }
        }
        end = System.currentTimeMillis(); // get ending time
        System.out.println("Ending time in milliseconds : " + end);
        System.out.println("Elapsed time: " + (end - start)+ " ms"); // LINE B    
    }
}
OUTPUT

Timing a for loop from 0 to 1000
Starting time in milliseconds : 1399877968125
Ending time in milliseconds : 1399877972375
Elapsed time: 4250 ms

DESCRIPTION

In the above program we have used System.currentTimeMillis method to find the time consumed by a part of a program. In the above program we have declared two variables start and end of long type and invoked System.currentTimeMillis method before beginning and ending of the for loop in order to find the time taken to execute the part of code and finally printed the time taken by the JVM to execute the part of code at LINE A.

THINGS TO TRY
  • Replace the part of code at LINE A with the below code and print the elapsed time.
    for(long i = 0; i , 100000000L; i++);
    The elapsed time should be Elapsed time: 10 ms

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App