About Privacy Need Help NOW?

Articles


Code:

View

Download

An Elapsed Time Class

Joe Sam Shirah


     Have you ever written code like this?


long lBeg = System.currentTimeMillis();

myMethod();

long lEnd = System.currentTimeMillis();
System.out.println( "Elapsed time is " + ( lEnd - lBeg ) );
So have I, even with all the tools we have available. And I will probably continue to have the need for something like this from time to time.

     Now it's not really a big deal to write three lines of code, but it is sort of a pain. In particular, unless I've used it recently, I have problems remembering if the System method is getMillis() or getCurrentMillis() or what. So I end up going to the javadocs to find that it is actually System.currentTimeMillis(). Why is that anyhow? What other millis would there be?

     Then, after getting my results, I throw the code away and go through the process again at a later date. From time to time I've thought of writing a small class to handle this, but never got around to it. So I've probably spent 50 or more times the amount of time it would have taken to write the class and be done with it. Well, I finally wrote a class like that and it looks like a perfect candidate for "Some Things Should Be Free."

     As you might imagine, there's nothing fancy here; the whole thing was mostly tedium. For most of the time, you would use the OS_ElapsedTime class as follows:


    OS_ElapsedTime et = new OS_ElapsedTime();
    et.begin();

    myMethod();

    et.endAndPrintElapsedMillis();
     I can tell that you are excited about this, but wait, there's more.

     The class is mutable. If you need it for another measure, just call begin() again. The method sets both the beginning and ending variables to the current millis. As you might expect, there are methods to get the beginning and ending values as millis or as a java.util.Date. You can also print the values as millis or Dates. And, there are several combo methods to beginAndPrintXXX() and endAndPrintXXX(). Last, there is a main method to exercise the class.

     And there you have it; use OS_ElapsedTime and never look up System.timeMillis() or whatever it is, ever again.



Copyright © 2000-2003, conceptGO