Reputation: 14109
Just out of interest, it would be nice to know how long my calculation programs run (e.g. Project Euler solutions). Either to see how many milliseconds I can squeeze out of the time by using different solutions, or to see how long it takes to crunch big numbers. Usually such a program ends with a System.out.println
, printing the answer. How can I put in another println
, which says "The program took seconds", or something like that (i.e. increment some variable by 0.001 every millisecond, then print it when the program is done)?
Upvotes: 0
Views: 733
Reputation: 23903
You could use:
long start = System.nanoTime();
// do something
long took = System.nanoTime() - start;
From documentation:
Returns the current value of the most precise available system timer, in nanoseconds. This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.
Upvotes: 1
Reputation: 2768
Take a look at this example: http://www.roseindia.net/java/java-get-example/get-execution-time.shtml Here's another complete but different implementation: http://www.mkyong.com/java/how-do-calculate-elapsed-execute-time-in-java/
Upvotes: 1
Reputation: 62439
You can get the total number of milliseconds easily, using the System.currentTimeMillis()
call (granularity depends on OS and may not be completely precise). Example:
long start = System.currentTimeMillis();
// portion of code
long stop = System.currentTimeMillis();
System.out.println("Time: " + (stop - start) + " ms");
Upvotes: 1