You can create an abstraction of the time control, which takes as an argument the action that needs to be performed, and measures and prints the time it takes to complete it.
Code:
interface Action<A> { public A perform(); } class Timer { public static <A> A time(final String description, final Action<A> action) { final long start = System.nanoTime(); final A result = action.perform(); final long end = System.nanoTime(); System.out.println(description + " - Time elapsed: " + (end - start) +"ns"); return result; } } class Main { public static void main(final String[] args) { final int factorialOf5 = Timer.time("Calculating factorial of 5", new Action<Integer>() { public Integer perform() { int result = 1; for(int i = 2; i <= 5; i++) { result *= i; } return result; } } ); System.out.println("Result: " + factorialOf5); } }
source share