In a less demanding usage scenario, you may need to know how many seconds a particular processing logic takes, and Java provides a convenient way to get the current time, and the middle part of the code runs by getting the difference of two points in time.
First, the way in which you get the current system time in Java is:
Long currenttime = System.currenttimemillis ();
This statement returns the number of milliseconds in the current time.
Now that we define a simple timer tool that does not include any validation logic, the code might look like this:
PackageCom.anivia.blog.util;/*** A simple time calculation tool *@authorMinlz *@versionSeptember 25, 2015 morning 10:21:56*/ Public classTimemeter {//Start Time PrivateLong StartTime; //End Time PrivateLong EndTime; //Duration PrivateLong Durationtime; PublicLong GetStartTime () {returnStartTime; } Public voidsetstarttime (Long startTime) { This. StartTime =StartTime; } PublicLong Getendtime () {returnEndTime; } Public voidsetendtime (Long endTime) { This. EndTime =EndTime; } PublicLong Getdurationtime () {returnDurationtime; } Public voidsetdurationtime (Long durationtime) { This. Durationtime =Durationtime; } //above is setter & Getter//start timing, get current time Public voidstart () { This. StartTime =System.currenttimemillis (); } //end timing, get current end time, and calculate travel value Public voidStop () { This. EndTime =System.currenttimemillis (); This. Setdurationtime ( This. EndTime- This. StartTime); }}
The method is called as follows:
PackageCom.anivia.blog.util;/** * @authorMinlz *@versionSeptember 25, 2015 morning 10:34:46*/ Public classMainutil { Public Static voidMain (string[] args) {timemeter timemeter=NewTimemeter (); Timemeter.start (); for(inti = 0; i < 1000000; i++) { //Do something} timemeter.stop (); System.out.println ("Duration Time:" +timemeter.getdurationtime ()); }}
This is the way this timemeter is used, but it has not yet been verified logically, a slightly more complex timer should be added to the current timer state validation, such as the start of the timer before stopping, multiple stops not allowed and so on.
The first time to write this, if there is a mistake, please friends to enlighten. Thank you
Simple Java_ to make an easy calculation time difference tool