The program timing function is not very useful, but when writing the sorting algorithm with the program timing function can be very intuitive to feel the time of the different sorting algorithm. (assuming, of course, that the amount of data involved is large enough)
There are two ways to get time in Java:
1. Use the Calendar class (package as Java.util.Calendar) to get the current time of the system for execution time judgment
2. Obtain the exact value of the current time through the System.currenttimemillis () or System.nanotime () method
It is important to note that the first method of the error is very large, sorting algorithm 5,000 of data to sort, when I repeat the timing, found that each time the timing structure will appear 5-10ms error, for the sorting algorithm, this error is quite large. Then is the System.currrenttimemillis () method, through the document, this method calls a native method, the obtained time precision will depend on the operating system implementation mechanism, that is to say, different operating systems will have different answers, awkward = =|
Finally is System.nanotime () method , this is more powerful, directly is the nanosecond-level timing method, than the above method of the accuracy of the 10^6 times, so for the time accuracy requirements are more comfortable with this method.
Usage
Suppose we need to test the time of the main () program:
Method 1:
Long start = calendar.getinstance (). Gettimeinmillis ();//start time, Unit is milliseconds
Main ();//program run
Long end = calendar.getinstance (). Gettimeinmillis ();//End time
Double spenttime = (double) End-start; The beginning of the end is the time spent
Method 2:
Like the idea above, it's just a different way of calling it.
Long start = System.nanotime ();//Unit is nanosecond
Main ();
Long end = System.nanotime ();
Double spenttime = (double) End-start;
This article is from the "Guardian" blog, please be sure to keep this source http://acevi.blog.51cto.com/13261784/1983844
Java Program run time calculation