Many elaborate programs need to calculate the time consumed by one execution.
Or, we often test the time it takes to read data.
The code is as follows: |
Copy code |
System. currentTimeMillis () can read the current time in milliseconds. The value is the current time minus 0 minutes 0 seconds on the first day of January 1, 1970. Package com. javaer. examples; Public class JavaTime { Public static void main (String [] args ){ Long t1 = System. currentTimeMillis (); For (int I = 0; I <10000; I ++ ){ System. out. println (I + "I am 111cn.net "); } Long t2 = System. currentTimeMillis (); Long t = t2-t1; System. out. println (t + "millisecond "); } } Output 9994 I am 111cn.net 9995 I am 111cn.net 9996 I am 111cn.net 9997 I am 111cn.net 9998 I am 111cn.net 9999 I am 111cn.net 125 ms |
Example:
The code is as follows: |
Copy code |
/** * Main. java * * @ Author 111cn.net */ Public class Main { /** * Calculate the number of milliseconds that have elapsed since the two time points. * */ Public void computeAndDisplayElapsedTime (){ Long startTime = System. currentTimeMillis (); For (int I = 0; I <10; I ++ ){ Try { Thread. sleep (60 ); } Catch (InterruptedException ex ){ Ex. printStackTrace (); } } Long endTime = System. currentTimeMillis (); Float seconds = (endTime-startTime)/1000F; System. out. println (Float. toString (seconds) + "seconds ."); } /** * Start the program * * @ Param args the command line arguments */ Public static void main (String [] args ){ New Main (). computeAndDisplayElapsedTime (); } } The output result is similar: 0.609 seconds. |
Example 3
The code is as follows: |
Copy code |
Package test; Import java. util .*; Public class Test2 { Public static void main (String [] args) { Long t1 = System. currentTimeMillis (); // Obtain the current time before sorting Try { Thread. currentThread (). sleep (3160 ); } Catch (Exception err) { } Long t2 = System. currentTimeMillis (); // Obtain the current time after sorting Calendar c = Calendar. getInstance (); C. setTimeInMillis (T2-T1 ); System. out. println ("time consumed:" + c. get (Calendar. MINUTE) + "points" + c. get (Calendar. SECOND) + "seconds" + c. get (Calendar. MILLISECOND) + "microsecond "); } } |