// TimingStuff.java
//
//Charles Cusack
//
// A simple example of how you can time things in Java
//
import java.io.PrintStream;
import java.util.Date;
public class TimingStuff
{
// Just a simple class variable.
int x;
public TimingStuff()
{
}
// How to time using one trial
public void timeOneTrial()
{
// Get start time
Date start = new Date();
// Do the work you want to time
blah();
// Get the end time
Date end = new Date();
// Compute and print the elapsed time
long time = end.getTime() - start.getTime();
System.out.println("It took "+time+" milliseconds");
}
// How to time using several trials---for added accuracy.
public void timeSeveralTrials(int numberTrials)
{
// Get the start time
Date start = new Date();
// Run several trials
for(int i = 0; i < numberTrials; i++)
blah();
// Get the end time
Date end = new Date();
// Get the elapsed time and divide by number of trials.
double time = (end.getTime() - start.getTime()*1.0)/numberTrials;
// Printf is a nifty way to format output in Java.
// I had a lengthy description of it, but then lost this
// source code and had to decompile it, and now I am too
// lazy to put in more information. So sue me.
// Anyway, google "java printf" for more info.
// Or go to Wikipedia--if it's on Wikipedia, you know it's true.
System.out.printf("It took %7.2f milliseconds", time);
}
// Another way to time multiple trials.
// The first method is probably better since if each
// time is too small, it may register as 0 each time,
// so the accumulated time might be too small.
public void timeSeveralTrialsB(int numberTrials)
{
long totalTime = 0;
for(int i = 0; i < numberTrials; i++)
{
Date start = new Date();
blah();
Date end = new Date();
totalTime += end.getTime() - start.getTime();
}
double time = totalTime*1.0/numberTrials;
System.out.printf("It took %7.2f milliseconds", time);
}
// Just a sample method to test
public void blah()
{
for(int i = 0; i < 100000; i++)
{
for(int j = 0; j < 10000; j++)
x++;
}
System.out.println(x);
}
}