How do I time a method's execution in Java?

It seems like it should be simpler than it is to get a method’s execution time. Is there a Timer utility class for things like timing how long a task takes, etc? Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.

There is always the old-fashioned way:

long startTime = System.nanoTime();

methodToTime();

long endTime = System.nanoTime();

 

long duration = endTime - startTime;
I go with the simple answer. Works for me.

 

long startTime = System.currentTimeMillis();

 

doReallyLongThing();

 

long endTime = System.currentTimeMillis();

 

System.out.println("That took " + (endTime - startTime) + " milliseconds");

It works quite well. The resolution is obviously only to the millisecond, you can do better with System.nanoTime(). There are some limitations to both (operating system schedule slices, etc.) but this works pretty well.

 

Average across a couple of runs (the more the better) and you'll get a decent idea.