4 // Created by Steven R. Loomis on 11/11/2005.
5 // Copyright 2005-2012 IBM. All rights reserved.
8 package com.ibm.icu.dev.util;
10 import java.util.Locale;
12 import com.ibm.icu.text.MessageFormat;
13 import com.ibm.icu.text.NumberFormat;
14 import com.ibm.icu.text.RuleBasedNumberFormat;
18 * Simple stopwatch timer.
19 * Usage: { ElapsedTimer et = new ElapsedTimer();
21 * System.out.println("It took " + et + " to do stuff."); }
23 * Advanced: { ElapsedTimer et = new ElapsedTimer("Thing2's time: {0}"); // messageformat pattern
25 * System.out.println(et.toString()); }
27 * More advanced: NumberFormat and/or MessageFormat can be provided in the constructor
29 public final class ElapsedTimer {
32 * Convenience method to print the elasped time (in milliseconds)
34 public static String elapsedTime(long start, long end) {
35 return diffTime(getFormat(), start, end);
38 public static String elapsedTime(long start) {
39 return diffTime(getFormat(), start, System.currentTimeMillis());
44 private long startTime = System.currentTimeMillis();
45 private NumberFormat myDurationFormat = null;
46 private MessageFormat myMsgFormat = null;
48 public ElapsedTimer() {
51 public ElapsedTimer(MessageFormat aMsgFmt) {
52 myMsgFormat = aMsgFmt;
55 public ElapsedTimer(NumberFormat aNumFmt) {
56 myDurationFormat = aNumFmt;
59 public ElapsedTimer(MessageFormat aMsgFmt, NumberFormat aNumFmt) {
60 myMsgFormat = aMsgFmt;
61 myDurationFormat = aNumFmt;
64 public ElapsedTimer(String pattern) {
65 myMsgFormat = new MessageFormat(pattern);
68 public ElapsedTimer(String pattern, NumberFormat aNumFmt) {
69 myMsgFormat = new MessageFormat(pattern);
70 myDurationFormat = aNumFmt;
74 * @return elapsed time in seconds since object creation
76 public final String toString() {
77 long endTime = System.currentTimeMillis();
78 String duration = diffTime(myDurationFormat, startTime, endTime);
79 if(myMsgFormat == null) {
82 return myMsgFormat.format(new Object[] {duration});
86 private static NumberFormat gFormat = null;
88 private static NumberFormat getFormat() {
90 gFormat = new RuleBasedNumberFormat(Locale.US,
91 RuleBasedNumberFormat.DURATION);
96 private static String diffTime(NumberFormat fmt, long start, long end) {
101 long age = end - start;
102 long diff = age/1000; // millis per second. Workaround ticket:7936 by using whole number seconds.
103 return fmt.format(diff);