Java Get Time of Execution

Last Updated On Thursday 11th Nov 2021

Java Time Method

currentTimeMillis

	public static long currentTimeMillis()
	
  • Returns the current time in milliseconds.
  • Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger.
  • For example, many operating systems measure time in units of tens of milliseconds.
	public class testProgram {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for(int n = 0 ; n < 50 ; n++){
            System.out.println("Test Program"); 
        }
        long end = System.currentTimeMillis();
        double total = (double)(end - start)/1000;
        System.out.println("Total " + total); 
    }
}
	
	Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
....
Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
Total 0.001
	

Java Trace Method Execution Time

nanoTime()

  • This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.
  • The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative).
	public static long nanoTime()
	

To compare two nanoTime values

	 long t0 = System.nanoTime();
 ...
 long t1 = System.nanoTime();
	
	public class testProgram {
    public static void main(String[] args) {
        long start = System.nanoTime();
        for(int n = 0 ; n < 50 ; n++){
            System.out.println("Test Program"); 
        }
        long end = System.nanoTime();
        double total = (double)(end - start)/1000;
        System.out.println("Total " + total); 
    }
}
	

Java get Time of Execution

	Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
....
Test Program
Test Program
Test Program
Test Program
Test Program
Test Program
Total 1230.3
	

References