0

I have a program that will throw a simple exception when it's completed, when that exception is thrown is there any way to treat it like a stop-watch and stop the timer and display how long it took to solve the problem given?

Thanks a lot!

HunderingThooves
  • 962
  • 8
  • 20
  • 33

3 Answers3

1

Milliseconds

System.currentTimeMillis() is a function that returns the current time in milliseconds. You can get invoke this function once when you start, and again when finished, then find the difference to determine the amount of time elapsed.

For example:

public void foo() {
    long startTime = System.currentTimeMillis();

    try {
        doStuff();
    } catch (Exception e) {
        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        System.out.println("This operation took " + elapsedTime + " milliseconds.");
    }
}

Nanoseconds

You can also use System.nanoTime() which is precise to nanosecond (rather than to the millisecond), but it is more limited in how much of a difference it can portray.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
  • This worked absolutely perfectly. I really appreciate the help! I ended up using nanoTime for my solution by the by. – HunderingThooves Nov 16 '11 at 15:54
  • Notes: (a) Your computer’s clock may not be fine-grained enough to capture nanoseconds despite your call to `nanoTime`. And therefore results may vary between various computers. (b) Be sure to use a `long` rather than `int` for nanoseconds (a common mistake). – Basil Bourque Mar 23 '14 at 07:14
  • See [this question and answers](http://stackoverflow.com/q/510462/642706) for discussion about call to `nanoTime`. – Basil Bourque Mar 23 '14 at 07:19
0

In the simplest case, use System.currentTimeMillis() to record the start and stop times (subtracting start from stop in the catch block). There are more complicated approaches with pretty interfaces. See, for example:

Just be sure that the timer is in scope whenever the exception is caught.

Community
  • 1
  • 1
Wayne
  • 59,728
  • 15
  • 131
  • 126
0

Exception handling is an especially poor method of flow control - much better to break out of a loop, set the loop conditional to false, or return out of your recursive method.

For your actual question, you can get the system time with System.currentTimeMillis() at the start of your program, and then again at the end, and compare. Note that the system call is only accurate to 15ms, so this is only really useful for long running programs.

Kane
  • 4,047
  • 2
  • 24
  • 33