import java.util.*; // has Date import java.text.*; // has NumberFormat // ---- class for timing execution ----------------------------------- public class Timer { // Returns elapsed seconds since start of program. public static double elapsedSeconds() { return ((double) (new Date()).getTime()) / 1000 ; } // Formats a double in a way suitable for values returned from // elapsedSeconds(): 4 decimal places, fixed-point form. public static String format(double t) { // For a more general and internationalizable approach, see NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(4); return nf.format(t); } // A little main program to test the above method. public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: " + "java Timer sleepSeconds"); System.exit(1); } int sleepTime = Integer.parseInt(args[0]); try { System.out.println("sleep for " + sleepTime + " seconds"); double startTime = elapsedSeconds(); Thread.sleep(sleepTime * 1000); System.out.println("time for one execution = " + format(elapsedSeconds() - startTime)); Thread.sleep(sleepTime * 1000); System.out.println("time for two executions = " + format(elapsedSeconds() - startTime)); } catch (InterruptedException e) { System.out.println("Something odd happened!: " + e); } } }