在學習spring的時候,看到關於統計時間的類,比較好奇,就記錄下來,以便以后用到可以直接使用
org.springframework.util.StopWatch
StopWatch該類在統計時間的時候,必須得前一個對象關閉才能創建新的StopWatch,並且在統計完成后,只需要將其輸出,就可以像報表一樣,顯示統計的時間
在開發中,常用於統計時間的是 使用 System.currentTimeMillis();進行統計,並且當執行完畢后,
還需要相減,才能得到最終時間值,不過,stopWatch差不多也是類似功能吧
public static void main(String[] args) throws InterruptedException { StopWatch sw = new StopWatch(); sw.start("讀取文件"); Thread.sleep(1000); sw.stop(); sw.start("文件刪除"); Thread.sleep(100); sw.stop(); sw.start("文件拷貝"); Thread.sleep(10); sw.stop(); System.out.println(sw.prettyPrint()); long stime =System.currentTimeMillis(); Thread.sleep(1000); long etime =System.currentTimeMillis(); System.out.println("執行時間:"+(etime-stime)); }
執行結果:
StopWatch '': running time (millis) = 1110
-----------------------------------------
ms % Task name
-----------------------------------------
01000 090% 讀取文件
00100 009% 文件刪除
00010 001% 文件拷貝
執行時間:1000
查看其內部源碼,我們可以看到,該類封裝了System.currentTimeMillis();在同一個stopWatch對象中,將每次stop都存放在linklist中,在統計的時候,再取出輸出
private final List<TaskInfo> taskList = new LinkedList<TaskInfo>(); public void start(String taskName) throws IllegalStateException { if (this.running) { throw new IllegalStateException("Can't start StopWatch: it's already running"); } this.startTimeMillis = System.currentTimeMillis(); this.running = true; this.currentTaskName = taskName; } /** * Stop the current task. The results are undefined if timing * methods are called without invoking at least one pair * {@link #start()} / {@link #stop()} methods. * @see #start() */ public void stop() throws IllegalStateException { if (!this.running) { throw new IllegalStateException("Can't stop StopWatch: it's not running"); } long lastTime = System.currentTimeMillis() - this.startTimeMillis; this.totalTimeMillis += lastTime; this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime); if (this.keepTaskList) { this.taskList.add(lastTaskInfo); } ++this.taskCount; this.running = false; this.currentTaskName = null; } /** * Return an array of the data for tasks performed. */ public TaskInfo[] getTaskInfo() { if (!this.keepTaskList) { throw new UnsupportedOperationException("Task info is not being kept!"); } return this.taskList.toArray(new TaskInfo[this.taskList.size()]); }