One, in milliseconds .
Long startTime = System.currenttimemillis (); Get Start time
DoSomething (); Code snippet for testing
Long endTime = System.currenttimemillis (); Get End time
SYSTEM.OUT.PRINTLN ("program Run Time:" + (Endtime-starttime) + "MS"); Output program run time
Second, the unit is in nanoseconds .
Long Starttime=system.nanotime (); Get Start time
DoSomething (); Code snippet for testing
Long Endtime=system.nanotime (); Get End time
SYSTEM.OUT.PRINTLN ("program Run Time:" + (Endtime-starttime) + "ns");
Time Conversion:
1 hours = 60 Minutes
1 minutes = 60 seconds
1 sec =1000 ms
1 ms =1000 μs
1 μs =1000 nanoseconds
1 nanoseconds =1000 leather seconds
We have a concatenation string in Java as an example
As an example, nanosecond is identical in the same way.
1 Final intN = 100000;2 3 4 5 //demonstrates inefficient methods for stitching strings6 LongStartime =System.currenttimemillis ();7String str = "*";8 for(inti = 0; i < N; i++) {9str + = "*";Ten One } A LongEndTime =System.currenttimemillis (); -System.out.println ("+ = spents:" + (Endtime-startime) + "milliseconds"); - the - //string stitching using stringbuffer (self-connected memory modification) is approximately 1000 times times the front (+ =) -Startime =System.currenttimemillis (); -StringBuffer str1 =NewStringBuffer ("*"); + for(inti = 0; i < N; i++) { -Str1.append ("*");//splicing Append + A } atEndTime =System.currenttimemillis (); -System.out.println ("StringBuffer Append Time:" + (Endtime-startime) + "MS"); - - - - //StringBuffer's enhanced version StringBuilder java1.5, StringBuilder efficiency is about 4 5 times times the stringbuffer of the front inStartime =System.currenttimemillis (); -StringBuilder str2 =NewStringBuilder ("*"); to for(inti = 0; i < N; i++) { +Str2.append ("*");//splicing Append - the } *EndTime =System.currenttimemillis (); $System.out.println ("StringBuilder Append Time:" + (Endtime-startime) + "MS");
This program is not completed please add to the reader's own.
The running result is as follows (now you know how inefficient it is to stitch strings with + =);
How to test the run time of a piece of code in Java