您好,登錄后才能下訂單哦!
一、最簡(jiǎn)單的計(jì)時(shí)
在我們的程序中不免需要對(duì)某一個(gè)運(yùn)算或者方法進(jìn)行計(jì)時(shí),以便我們來觀察該運(yùn)算或方法是否符合我們的預(yù)期,所以在我們剛開始接觸 Java 的時(shí)候都能寫出類似下面這樣的代碼來計(jì)時(shí):
public static void main(String[] args) { Long startTime = System.currentTimeMillis(); doSomeThing(); Long endTime = System.currentTimeMillis(); Long elapsedTime = (endTime - startTime) / 1000; System.out.println("總共耗時(shí):" + elapsedTime + "s"); } // 用于模擬一些操作 private static void doSomeThing() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }
事實(shí)上這樣也并沒有什么問題,并且也能夠運(yùn)行的很好,但是有一點(diǎn)不太好的就是,自己關(guān)注了太多輸出的信息,下面我們來認(rèn)識(shí)一種更優(yōu)雅的一種計(jì)時(shí)方式;
二、StopWatch 類
想要使用它,首先你需要在你的 Maven 中引入 Spring 核心包,當(dāng)然 Spring MVC 和 Spring Boot 都已經(jīng)自動(dòng)引入了該包:
<!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency>
現(xiàn)在我們計(jì)時(shí)的姿勢(shì)或許就會(huì)變成以下這樣:
public static void main(String[] args) { StopWatch clock = new StopWatch(); clock.start("開始任務(wù)一"); doSomeThing(); clock.stop(); clock.start("開始任務(wù)二"); doSomeThing(); clock.stop(); System.out.println(clock.prettyPrint()); } // 用于模擬一些操作 private static void doSomeThing() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }
在最后我們使用 StopWatch 類自帶的 prettyPrint() 方法類格式化我們的輸出,運(yùn)行程序你會(huì)發(fā)現(xiàn)你的程序輸出了這樣的東西:
StopWatch '': running time (millis) = 2009 ----------------------------------------- ms % Task name ----------------------------------------- 01005 050% 開始任務(wù)一 01004 050% 開始任務(wù)二
不僅有總用時(shí),還有每個(gè)任務(wù)分別的占用時(shí)間和占用時(shí)間的百分比,這或許就會(huì)比我們自己輸出要優(yōu)雅那么一些;
StopWatch 類是怎么實(shí)現(xiàn)的呢?
當(dāng)你戳開 StopWatch 的源碼,你會(huì)在總共不到 200 行的代碼里看到熟悉的東西:
public void start(String taskName) throws IllegalStateException { if (this.currentTaskName != null) { throw new IllegalStateException("Can't start StopWatch: it's already running"); } else { this.currentTaskName = taskName; this.startTimeMillis = System.currentTimeMillis(); } } public void stop() throws IllegalStateException { if (this.currentTaskName == null) { 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.currentTaskName = null; } }
你會(huì)發(fā)現(xiàn)該類使用 LinkedList 實(shí)現(xiàn)了一個(gè)叫做 taskList 的隊(duì)列,然后每一次開始同樣也是使用 System.currentTimeMillis() 方法來獲取時(shí)間,每次除了計(jì)算耗時(shí)也會(huì)構(gòu)建一個(gè)描述當(dāng)前任務(wù)的 TaskInfo 對(duì)象,并把它放入 taskList 隊(duì)列中。
當(dāng)執(zhí)行 prettyPrint() 方法的時(shí)候,就從 taskList 隊(duì)列中依次取出任務(wù),然后做些格式化的操作:
public String shortSummary() { return "StopWatch '" + this.getId() + "': 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[] var4 = this.getTaskInfo(); int var5 = var4.length; for(int var6 = 0; var6 < var5; ++var6) { StopWatch.TaskInfo task = var4[var6]; 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(); }
摁,新姿勢(shì) get √。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。