You can use an “Execute Around” idiom similar to this by Jon Skeet, with the timing surrounding your method call:
public class StackOverflowTest {
public static void main(String[] args){
StackOverflowTest test = new StackOverflowTest();
test.timeMethod(test::getAllProducts);
test.timeMethod(test::getAllClients);
test.timeMethod(test::getAllSymbols);
}
void getAllProducts(){
System.out.println("getting all Products");
}
void getAllClients(){
System.out.println("getting all Clients");
}
void getAllSymbols(){
System.out.println("getting all Symbols");
}
// The "Execute Around" method
void timeMethod(JustDoIt justDoIt){
long start = System.nanoTime();
try {
justDoIt.doIt();
} finally {
long end = System.nanoTime();
System.out.println(" Time: " + (end - start) / 1000 + " microseconds"");
}
}
}
@FunctionalInterface
interface JustDoIt {
void doIt();
}
Prints:
getting all Products
Time: 1817 microseconds
getting all Clients
Time: 421 microseconds
getting all Symbols
Time: 418 microseconds
If you don't want your own Interface, you can replace it with a Runnable
. This example also uses System.currentTimeMillis()
instead of System.nanoTime()
:
void timeMethod(Runnable toRun){
long start = System.currentTimeMillis();
try{
toRun.run();
} finally {
long end = System.currentTimeMillis();
System.out.println(" Time: " + (end - start) + " miliseconds");
}
}