Sunday, June 11, 2017

Measuring Execution Time of a Method in Java

Old fashioned Way
System.currentTimeMillis()
Accuracy is only in milli seconds, so if you are timing a method which is quite small then you might not get good results.

List<Integer> input = getInputList();
long t1 = System.currentTimeMillis();
Collections.sort(input);
long t2 = System.currentTimeMillis();
System.out.println("Time Taken ="+ (t2-t1) + " in milli seconds");

Using Nano seconds
System.nanoTime()
Preferred approach (compared to first one). But do keep in mind that not all systems will provide accuracy in nano time.

List<Integer> input = getInputList();
long t1 = System.nanoTime();
Collections.sort(input);
long t2 = System.nanoTime();
System.out.println("Time Taken ="+ (t2-t1) + " in nano seconds");

Java 8
List<Integer> input = getInputList();
Instant start = Instant.now();
Collections.sort(input);
Instant end = Instant.now();
System.out.println("Time Taken ="+ Duration.between(start, end) + " in nano seconds");

Guava

Stopwatch stopwatch = new Stopwatch().start();
Collections.sort(input);
stopwatch.stop();


No comments:

Post a Comment