Feed on
Posts
Comments

I often find myself writing lightweight performance tests as part of a suite of the unit tests, to make sure that my code hasn’t been written in a way to destroy the performance of an application. I also create performance tests as a standalone Application to test (for instance) how many HttpServletRequest/Response calls can be made over a certain period of time.

My requirements are normally simple, and rarely have a strong need to be COMPLETELY perfect; i.e. the actual calls to and from the timer can cause a slight time loss in the actual application, but frankly I’m willing to put up with this in most circumstances. The “TesterTimer” class featured below is pretty damned efficient, especially if you never call the “elapsed(id)” method, since the start and stop happen pretty much outside the application being tested. Here is the fully commented code with a demonstration “main” class:

import java.util.Hashtable;

/**
* TestTimer Class, with methods to calculate the time to run
* particular tests. Multiple events can be mapped at once
* to a hashtable. Each event is retrieved by the id passed in
* to each available static method.
*
* @author dan@gurovich.com
* @version 1.0
* @since Sep 6, 2007
*/
public class TesterTimer {

//~ Static fields/initializers ***********************************

/**
* Hashtable holding various timer events, mapped to ids.
*/
private static final Hashtable startTime = new Hashtable()

//~ Methods ******************************************************

/**
* Stops the Timer, and removes the time.
* Returns the elapsed time.
*
* @param id — The id of the timer.
*
* @return long value of the elapsed time in milliseconds.
*/
public static long elapsed(String id) {|
return System.currentTimeMillis()
- ((Long) startTime.get(id)).longValue();
}
/**
* Returns a formatted Elapsed time string.
*
* @param time — long value passed in,
* presumed to be milliseconds.
*
* @return String formatted similar to ” 2h :1m :53s :443ms “.
*/
public static String returnFormattedTime(long time) {

//the seconds
long seconds = time / 1000;

//the hours
long hours = seconds / 3600;

//seconds adjusted after hours
seconds = seconds % 3600;

//the minutes
long minutes = seconds / 60;

//seconds adjusted after minutes
seconds = seconds % 60;

//milliseconds left over.
long millis = time % 1000;

// Print out the results
return new StringBuffer().append(hours).append(“h :”)
.append(minutes).append(“m :”).append(
seconds).append(“s :”).append(millis).append(“ms”)
.toString();
}

/**
* Starts the timer for a particular id, adds it to a Hashtable.
*
* @param id — the id of the timer for the Hashtable.
*/
public static void start(String id) {
startTime.put(id, new Long(System.currentTimeMillis()));
}
/**
* Stops the Timer, and removes the time. Returns the elapsed time.
*
* @param id — The id of the timer.
*
* @return long value of the elapsed time in milliseconds.
*/
public static long stop(String id) {
return System.currentTimeMillis()
- ((Long) startTime.remove(id)).longValue();
}
/**
* Main method to do some math and take up some time.
*
* @param args — no args digested.
*/
public static void main(String[] args) {
TesterTimer.start(“hello”);

for (int h = 0; h < 20; h++) {
for (int i = 0; i < 32000000; i++) {
int j = i / 25;
}

if ((h % 4) == 0) {
System.out.println(
TesterTimer.returnFormattedTime(
TesterTimer.elapsed(“hello”)));
}
h++;
}

long t = TesterTimer.stop(“hello”);
System.out.println(“Timer: ” + t);
System.out.println(“FMT Timer: ” + TesterTimer.returnFormattedTime(t))
}
}

* TestTimer Class, with methods to calculate the time to run
* particular tests. Multiple events can be mapped at once
* to a hashtable. Each event is retrieved by the id passed in
* to each available static method.
*
* @author dan@gurovich.com
* @version 1.0
* @since Sep 6, 2007
*/
public class TesterTimer {
//~ Static fields/initializers ***********************************

/**
* Hashtable holding various timer events, mapped to ids.
*/
private static final Hashtable startTime = new Hashtable();

//~ Methods ******************************************************

/**
* Stops the Timer, and removes the time.
* Returns the elapsed time.
*
* @param id — The id of the timer.
*
* @return long value of the elapsed time in milliseconds.
*/
public static long elapsed(String id) {
return System.currentTimeMillis()
- ((Long) startTime.get(id)).longValue();
}

/**
* Returns a formatted Elapsed time string.
*
* @param time — long value passed in,
* presumed to be milliseconds.
*
* @return String formatted similar to ” 2h :1m :53s :443ms “.
*/
public static String returnFormattedTime(long time) {
//the seconds
long seconds = time / 1000;
//the hours
long hours = seconds / 3600;
//seconds adjusted after hours
seconds = seconds % 3600;
//the minutes
long minutes = seconds / 60;
//seconds adjusted after minutes
seconds = seconds % 60;
//milliseconds left over.
long millis = time % 1000;

// Print out the results
return new StringBuffer().append(hours).append(“h :”)
.append(minutes).append(“m :”).append(
seconds).append(“s :”).append(millis).append(“ms”)
.toString();
}

/**
* Starts the timer for a particular id, adds it to a Hashtable.
*
* @param id — the id of the timer for the Hashtable.
*/
public static void start(String id) {
startTime.put(id, new Long(System.currentTimeMillis()));
}

/**
* Stops the Timer, and removes the time.
* Returns the elapsed time.
*
* @param id — The id of the timer.
*
* @return long value of the elapsed time in milliseconds.
*/
public static long stop(String id) {
return System.currentTimeMillis()
- ((Long) startTime.remove(id)).longValue();
}

/**
* Main method to do some math and take up some time.
*
* @param args — no args digested.
*/
public static void main(String[] args) {
TesterTimer.start(“hello”);

for (int h = 0; h < 20; h++) {
for (int i = 0; i < 32000000; i++) {
int j = i / 25;
}
int foo = h % 4;
if (foo == 0) {
System.out.println(
TesterTimer.returnFormattedTime(
TesterTimer.elapsed(“hello”)));
}
h++;
}
long t = TesterTimer.stop(“hello”);
System.out.println(“Timer: ” + t);
System.out.println(
“FMT Timer: ” + TesterTimer.returnFormattedTime(t));
}
}

The timer has three static working methods – start(id), elapsed(id), and stop(id). The start(id) method is void and starts the timer for a particular event mapped to an id. The id is a key within a Hashtable that records a starting time. When elapsed(id) is called, the value returned is a long primitive which is the start time subtracted from the current time, returning a milliseconds value. With elapsed(id) the key isn’t removed so one may keep the timer running. stop() returns the same value as elapsed(id), but stop(id) removes the key value mapped to the id, thereby “stopping” the timer completely.

Create PDF    Send article as PDF   

2 Responses to “Creating a Java TesterTimer for Performance Testing.”

  1. Brad White says:

    Just have to say a quick thanks for posting this. Saved me time doing something that I really didn’t want to and it works well.

    There are some errors in your post. First, I think you pasted everything twice, so everything is a duplicate. Second, there is a pipe at: “public static long elapsed(String id) {|”.

    Thanks again.

  2. Danilo says:

    I’m not surprised if it didn’t come up twice. The editing platform on WordPress isn’t the best for posting code. Thanks for drilling though it. I’ll see if I can find that pipe…

Leave a Reply

Bad Behavior has blocked 225 access attempts in the last 7 days.