Current time in millis second and nano second

In this chapter you will learn:

  1. How to get current time in nano seconds
  2. How to get current time in millis seconds
  3. How to time the performance of a for loop

Current nano time

static long nanoTime() from System class Returns the current value of the most precise available system timer, in nanoseconds.

public class Main {
//from j  a  v  a 2  s .  co m
  public static void main(String args[]) {
    System.out.println(System.nanoTime());
  }
}

The output:

get current time in millis seconds

static long currentTimeMillis() from System class Returns the current time in milliseconds.

public class Main {
// j a v a  2s  .co  m
  public static void main(String args[]) {
    System.out.println(System.currentTimeMillis());
  }
}

The output:

Time a for loop

The following code uses the System.currentTimeMillis() to check the performance of a for loop.

public class Main {
  public static void main(String args[]) {
    long start, end;
//from   j  a  v  a2s . co  m
    System.out.println("Timing a for loop from 0 to 1,000,000");

   start = System.currentTimeMillis(); // get starting time
    for (int i = 0; i < 9999999; i++)
      ;
    end = System.currentTimeMillis(); // get ending time

    System.out.println("Elapsed time: " + (end - start));
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Get a Random UUID
Home » Java Tutorial » Utility Classes
Java standard stream
Java system property get and set
Current time in millis second and nano second
Random UUID
JVM memory
JVM garbage collector
JVM shutting down
Processor count
OS system commands
Random class
Random value
Random value range
Compile Java source code
Timer and TimerTask