Performance Timing

Problem

You need to know how long a Java program takes to run.

Solution

Call System.currentTimeMillis( ) before and after invoking the target class dynamically.

Discussion

The simplest technique is to save the JVM’s accumulated time before and after dynamically loading a main program, and calculating the difference between those times. Code to do just this is presented in Example 25-7; for now, just remember that we have a way of timing a given Java class.

One way of measuring the efficiency of a particular operation is to run it many times in isolation. The overall time the program takes to run thus approximates the total time of many invocations of the same operation. Gross numbers like this can be compared if you want to know which of two ways of doing something is more efficient. Consider the case of string concatenation versus println( ). The code:

println("Time is " + n.toString(  ) + " seconds");

creates a StringBuffer, appends the string "Time is ", the value of n as a string, and " seconds", and finally converts the finished StringBuffer to a String and passes that to println( ). Suppose you have a program that does a lot of this, such as a Java servlet (see Chapter 18) that creates a lot of HTML this way, and you expect (or at least hope) that your web site will be sufficiently busy that doing this efficiently will make a difference. There are two ways of thinking about this:

  • Theory A: This string concatenation is inefficient.

  • Theory B: String concatenation ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.