Monday 10 March 2014

Perfect Timing. A Timer Class to estimate performance.

When testing the performance of your code it can be useful to use  the currentTimeMillis() method in System. Usually you would use it as follows:


I found it useful to create a Timer class and instantiate a Timer object in my production code. This allows me to drag my Timer.class into new projects and use saved snippets to instantiate and call the methods of the class. i can therefor easily remove the testing code before release. I can also add various methods in the class that I can call if and when needed rather then constantly rewriting calculations.

Here is a basic timer classs with a little extra thrown in  the toString() method:


and this is a basic test program. You should alter the duration of the loop to see the results.


It should be noted that currentTimeMillis() is not the most granular of  timers  and reults will vary. You should run it multiple times to get a more accurate representation of the time taken, this also lets the compiler optimize the bytecode. Using TimeUnit from java.util.concurrent allows conversion of time units for a "plain english" representation of time taken. The TimeUnit is overkill here, it is only necessary for longer durations (> hour), but there is no harm in highlighting its existence and usefulness.

Simples!

No comments:

Post a Comment