Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2006

Tip: Looking for answers? Try searching our database.

What's the Best Way to Time a Program's Execution?

Thread view: 
kvnsmnsn@hotmail.com - 29 Mar 2006 02:11 GMT
I would like to tell how long it takes a piece of code I've written to
execute.  I thought class <Date> might help me with that, so to test
that I wrote the following snippet of code:

    import java.util.Date;

    public class Loop
    {
      public static void main ( String[] arguments)
      {
        Date time;
        long start, loops, lp;

        if (arguments.length == 1)
        { loops = 1000000 * Long.parseLong( arguments[ 0]);
          time  = new Date();
          start = time.getTime();
          for (lp = 0; lp < loops; lp++);
          System.out.println
            ( loops + " loops last " + (time.getTime() - start)
                    + " milliseconds.");
        }
        else
        { System.out.println
            ( "Usage is\n  java Loop <millions-of-loops>");
        }
      }
    }

But apparently once I initialize <time> using the <Date()> construc-
tor, its <getTime()> method always returns the same value, so I always
get zero printed out.

Now I'm guessing that if I created two <Date> objects with that con-
structor, one before the loop and one after, then I'd get the number
of milliseconds I want.  Is that the only way to time my loop's opera-
tion, or am I missing something?

                               ---Kevin Simonson

"You'll never get to heaven, or even to LA,
if you don't believe there's a way."
from _Why Not_
JeffLowery - 29 Mar 2006 02:40 GMT
Use Calendar:

Calendar cal =
Calendar.getInstance().getTime();

then
cal.clear();
cal.getTime();
opalpa@gmail.com opalinski from opalpaweb - 29 Mar 2006 03:02 GMT
import java.util.*;
import java.text.*;
/**
  timing tool
*/
public final class Stopwatch {
 private String startedStr, stoppedStr;
 private long startedAt, stoppedAt, elapsed;
 final static private SimpleDateFormat format
   = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
 public Stopwatch() {
   stoppedStr = "not yet stopped";
   stoppedAt = -1;
   elapsed = -1;
   startedAt = System.currentTimeMillis();
   startedStr = format.format(startedAt);
 }
 public String toString() {
   return "Stopwatch("+startedStr+", "+stoppedStr+",
"+elapsedSeconds()+" seconds)";
 }
 public double elapsedSeconds() {
   if (stoppedAt == -1)
     throw new IllegalStateException("not stopped");
   double secs = ((double)elapsed) / 1000.0;
   return secs;
 }
 synchronized public long stop() {
   if (stoppedAt != -1)
     throw new IllegalStateException("already stopped");
   stoppedAt = System.currentTimeMillis();
   stoppedStr = format.format(stoppedAt);
   elapsed = stoppedAt - startedAt;
   return elapsed;
 }
}

Opalinski
opalpa@gmail.com
http://www.geocities.com/opalpaweb/
Real Gagnon - 29 Mar 2006 03:04 GMT
> I would like to tell how long it takes a piece of code I've written to
> execute.  I thought class <Date> might help me with that, so to test
> that I wrote the following snippet of code:

long start = System.currentTimeMillis();
...
long end = System.currentTimeMillis();

long duration = end - start;
System.out.println(duration + " ms ");

On PC, the time resolution is not to high, used to be around 55ms.

Bye.
Signature

Real Gagnon  from  Quebec, Canada
* Looking for Java or PB code examples ? Visit Real's How-to  
* http://www.rgagnon.com/howto.html

Roedy Green - 29 Mar 2006 03:55 GMT
On Wed, 29 Mar 2006 02:04:56 GMT, Real Gagnon
<realgagnon+usenet_@_yahooSpamIsBadSstripunderscore.com> wrote, quoted
or indirectly quoted someone who said :

>On PC, the time resolution is not to high, used to be around 55ms.

for higher res, see System.nanoTime
See http://mindprod.com/jgloss/time.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 29 Mar 2006 03:05 GMT
>I would like to tell how long it takes a piece of code I've written to
>execute.  I thought class <Date>

see http://mindprod.com/jgloss/time.html
and http://mindprod.com/jgloss/benchmark.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Lee Weiner - 29 Mar 2006 03:13 GMT
>I would like to tell how long it takes a piece of code I've written to
>execute.  I thought class <Date> might help me with that, so to test
>that I wrote the following snippet of code:

<snip code>

>But apparently once I initialize <time> using the <Date()> construc-
>tor, its <getTime()> method always returns the same value, so I always
[quoted text clipped - 4 lines]
>of milliseconds I want.  Is that the only way to time my loop's opera-
>tion, or am I missing something?

There's an easier way.  The System class has a static method
"currentTimeMillis()", that returns a long containing the number of
milliseconds that have elapsed since midnight.  Call it once at the beginning,
call it again at the end, and subtract.  As long as you're not performing the
test at exactly midnight, you shouldn't have a problem.

Lee Weiner
lee AT leeweiner DOT org
opalpa@gmail.com opalinski from opalpaweb - 29 Mar 2006 11:55 GMT
> The System class has a static method
> "currentTimeMillis()", that returns a long containing the number of
> milliseconds that have elapsed since midnight.

midnight, January 1, 1970 UTC.

> As long as you're not performing the
> test at exactly midnight, you shouldn't have a problem.

The method does not reset at midnight.  Using at midnight is fine.

Opalinski
opalpa@gmail.com
http://www.geocities.com/opalpaweb/
Oliver Wong - 29 Mar 2006 18:38 GMT
> I would like to tell how long it takes a piece of code I've written to
> execute.

   You want the "Best Way"? Don't use java; use the facilities in your
operating system. Your OS can take into account factors such as your program
not getting 100% of the CPU, but rather sharing it with other processes, for
example. OSes have to time the execution of programs anyway to do
time-slicing so that every program gets a chance at the CPU. Check the
documentation for your OS to see what facilities are available to you.

   - Oliver


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.