Current Time Millis Java


Current Time Millis: To know the performance or speed of doing a task, the designers added currentTimeMillis() method in System class, that too as static so that programmer can call the method without object creation.

Following is the method signature of Current Time Millis as defined in the System class.

public static native long currentTimeMillis();

Observe, the method returns a long data type as the system time is definitely more than an int value. The method returns the system current time in milliseconds.

In the following program, a for loop is iterated for 1000000000 times and time is measured before and after for loop. Then printed the time taken in Current Time Millis method to execute the for loop.

public class Demo
{
  public static void main(String args[])
  {
    long startTime = System.currentTimeMillis(); 

    for(int i = 0; i < 1000000000; i++)  {      }

    long endTime = System.currentTimeMillis();                         // observe, Current Time Millis

    System.out.println("Time read before for loop in milliseconds : " + startTime);
    System.out.println("Time read after for loop in milliseconds: " + endTime);
    System.out.println("Time taken in milliseconds: " + (endTime - startTime));
   }
}


Current Time Millis
Output screen on Current Time Millis Java

Leave a Comment

Your email address will not be published.