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!
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!
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.");
}
}
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.
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.
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.