小編這次要給大家分享的是如何使用Spring計時器StopWatch,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
在新沂等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務理念,為客戶提供成都網(wǎng)站設計、成都網(wǎng)站建設 網(wǎng)站設計制作定制網(wǎng)站設計,公司網(wǎng)站建設,企業(yè)網(wǎng)站建設,品牌網(wǎng)站制作,網(wǎng)絡營銷推廣,外貿(mào)網(wǎng)站建設,新沂網(wǎng)站建設費用合理。
StopWatch是位于org.springframework.util包下的一個工具類,通過它可方便的對程序部分代碼進行計時(ms級別),適用于同步單線程代碼塊。
正常情況下,我們?nèi)绻枰茨扯未a的執(zhí)行耗時,會通過如下的方式進行查看:
public static void main(String[] args) throws InterruptedException { StopWatchTest.test0(); // StopWatchTest.test1(); } public static void test0() throws InterruptedException { long start = System.currentTimeMillis(); // do something Thread.sleep(100); long end = System.currentTimeMillis(); long start2 = System.currentTimeMillis(); // do something Thread.sleep(200); long end2 = System.currentTimeMillis(); System.out.println("某某1執(zhí)行耗時:" + (end - start)); System.out.println("某某2執(zhí)行耗時:" + (end2 - start2)); }
運行結(jié)果:
某某1執(zhí)行耗時:105
某某2執(zhí)行耗時:203
該種方法通過獲取執(zhí)行完成時間與執(zhí)行開始時間的差值得到程序的執(zhí)行時間,簡單直接有效,但想必寫多了也是比較煩人的,尤其是碰到不可描述的代碼時,會更加的讓人忍不住多寫幾個bug聊表敬意,而且該結(jié)果也不夠直觀,此時會想是否有一個工具類,提供了這些方法,或者自己寫個工具類,剛好可以滿足這種場景,并且把結(jié)果更加直觀的展現(xiàn)出來。
首先我們的需求如下:
根據(jù)該需求,我們可直接使用org.springframework.util包下的一個工具類StopWatch,通過該工具類,我們對上述代碼做如下改造:
public static void main(String[] args) throws InterruptedException { // StopWatchTest.test0(); StopWatchTest.test1(); } public static void test1() throws InterruptedException { StopWatch sw = new StopWatch("test"); sw.start("task1"); // do something Thread.sleep(100); sw.stop(); sw.start("task2"); // do something Thread.sleep(200); sw.stop(); System.out.println("sw.prettyPrint()~~~~~~~~~~~~~~~~~"); System.out.println(sw.prettyPrint()); }
運行結(jié)果:
sw.prettyPrint()~~~~~~~~~~~~~~~~~
StopWatch 'test': running time (millis) = 308
-----------------------------------------
ms % Task name
-----------------------------------------
00104 034% task1
00204 066% task2
start開始記錄,stop停止記錄,然后通過StopWatch的prettyPrint方法,可直觀的輸出代碼執(zhí)行耗時,以及執(zhí)行時間百分比,瞬間感覺比之前的方式高大上了一個檔次。
除此之外,還有以下兩個方法shortSummary,getTotalTimeMillis,查看程序執(zhí)行時間。
運行代碼及結(jié)果:
System.out.println("sw.shortSummary()~~~~~~~~~~~~~~~~~"); System.out.println(sw.shortSummary()); System.out.println("sw.getTotalTimeMillis()~~~~~~~~~~~~~~~~~"); System.out.println(sw.getTotalTimeMillis());
運行結(jié)果
sw.shortSummary()~~~~~~~~~~~~~~~~~
StopWatch 'test': running time (millis) = 308
sw.getTotalTimeMillis()~~~~~~~~~~~~~~~~~
308
其實以上內(nèi)容在該工具類中實現(xiàn)也極其簡單,通過start與stop方法分別記錄開始時間與結(jié)束時間,其中在記錄結(jié)束時間時,會維護一個鏈表類型的tasklist屬性,從而使該類可記錄多個任務,最后的輸出也僅僅是對之前記錄的信息做了一個統(tǒng)一的歸納輸出,從而使結(jié)果更加直觀的展示出來。
StopWatch優(yōu)缺點:
優(yōu)點:
缺點:
spring中StopWatch源碼實現(xiàn)如下:
import java.text.NumberFormat; import java.util.LinkedList; import java.util.List; public class StopWatch { private final String id; private boolean keepTaskList = true; private final List<TaskInfo> taskList = new LinkedList(); private long startTimeMillis; private boolean running; private String currentTaskName; private StopWatch.TaskInfo lastTaskInfo; private int taskCount; private long totalTimeMillis; public StopWatch() { this.id = ""; } public StopWatch(String id) { this.id = id; } public void setKeepTaskList(boolean keepTaskList) { this.keepTaskList = keepTaskList; } public void start() throws IllegalStateException { this.start(""); } public void start(String taskName) throws IllegalStateException { if (this.running) { throw new IllegalStateException("Can't start StopWatch: it's already running"); } else { this.startTimeMillis = System.currentTimeMillis(); this.running = true; this.currentTaskName = taskName; } } public void stop() throws IllegalStateException { if (!this.running) { throw new IllegalStateException("Can't stop StopWatch: it's not running"); } else { long lastTime = System.currentTimeMillis() - this.startTimeMillis; this.totalTimeMillis += lastTime; this.lastTaskInfo = new StopWatch.TaskInfo(this.currentTaskName, lastTime); if (this.keepTaskList) { this.taskList.add(this.lastTaskInfo); } ++this.taskCount; this.running = false; this.currentTaskName = null; } } public boolean isRunning() { return this.running; } public long getLastTaskTimeMillis() throws IllegalStateException { if (this.lastTaskInfo == null) { throw new IllegalStateException("No tasks run: can't get last task interval"); } else { return this.lastTaskInfo.getTimeMillis(); } } public String getLastTaskName() throws IllegalStateException { if (this.lastTaskInfo == null) { throw new IllegalStateException("No tasks run: can't get last task name"); } else { return this.lastTaskInfo.getTaskName(); } } public StopWatch.TaskInfo getLastTaskInfo() throws IllegalStateException { if (this.lastTaskInfo == null) { throw new IllegalStateException("No tasks run: can't get last task info"); } else { return this.lastTaskInfo; } } public long getTotalTimeMillis() { return this.totalTimeMillis; } public double getTotalTimeSeconds() { return (double) this.totalTimeMillis / 1000.0D; } public int getTaskCount() { return this.taskCount; } public StopWatch.TaskInfo[] getTaskInfo() { if (!this.keepTaskList) { throw new UnsupportedOperationException("Task info is not being kept!"); } else { return (StopWatch.TaskInfo[]) this.taskList.toArray(new StopWatch.TaskInfo[this.taskList.size()]); } } public String shortSummary() { return "StopWatch '" + this.id + "': running time (millis) = " + this.getTotalTimeMillis(); } public String prettyPrint() { StringBuilder sb = new StringBuilder(this.shortSummary()); sb.append('\n'); if (!this.keepTaskList) { sb.append("No task info kept"); } else { sb.append("-----------------------------------------\n"); sb.append("ms % Task name\n"); sb.append("-----------------------------------------\n"); NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumIntegerDigits(5); nf.setGroupingUsed(false); NumberFormat pf = NumberFormat.getPercentInstance(); pf.setMinimumIntegerDigits(3); pf.setGroupingUsed(false); StopWatch.TaskInfo[] var7; int var6 = (var7 = this.getTaskInfo()).length; for (int var5 = 0; var5 < var6; ++var5) { StopWatch.TaskInfo task = var7[var5]; sb.append(nf.format(task.getTimeMillis())).append(" "); sb.append(pf.format(task.getTimeSeconds() / this.getTotalTimeSeconds())).append(" "); sb.append(task.getTaskName()).append("\n"); } } return sb.toString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(this.shortSummary()); if (this.keepTaskList) { StopWatch.TaskInfo[] var5; int var4 = (var5 = this.getTaskInfo()).length; for (int var3 = 0; var3 < var4; ++var3) { StopWatch.TaskInfo task = var5[var3]; sb.append("; [").append(task.getTaskName()).append("] took ").append(task.getTimeMillis()); long percent = Math.round(100.0D * task.getTimeSeconds() / this.getTotalTimeSeconds()); sb.append(" = ").append(percent).append("%"); } } else { sb.append("; no task info kept"); } return sb.toString(); } public static final class TaskInfo { private final String taskName; private final long timeMillis; TaskInfo(String taskName, long timeMillis) { this.taskName = taskName; this.timeMillis = timeMillis; } public String getTaskName() { return this.taskName; } public long getTimeMillis() { return this.timeMillis; } public double getTimeSeconds() { return (double) this.timeMillis / 1000.0D; } } }
看完這篇關于如何使用Spring計時器StopWatch的文章,如果覺得文章內(nèi)容寫得不錯的話,可以把它分享出去給更多人看到。
網(wǎng)站標題:如何使用Spring計時器StopWatch
網(wǎng)站網(wǎng)址:http://jinyejixie.com/article2/ghdsoc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、自適應網(wǎng)站、電子商務、品牌網(wǎng)站制作、手機網(wǎng)站建設、響應式網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)