亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java中StopWatch的使用示例詳解

 更新時間:2025年04月02日 11:17:24   作者:我自是年少韶華傾負  
stopWatch 是org.springframework.util 包下的一個工具類,使用它可直觀的輸出代碼執(zhí)行耗時,以及執(zhí)行時間百分比,這篇文章主要介紹了Java中StopWatch的使用詳解,需要的朋友可以參考下

stopWatch 是org.springframework.util 包下的一個工具類,使用它可直觀的輸出代碼執(zhí)行耗時,以及執(zhí)行時間百分比。

在未使用這個工具類之前,如果我們需要統(tǒng)計某段代碼的耗時,我們會這樣寫:

public static void main(String[] args) throws InterruptedException {
    test0();
}
public static void test0() throws InterruptedException {
    long start = System.currentTimeMills();
    // do something
    Thread.sleep(100);
    long end = System.currentTimeMills();
    long start2 = System.currentTimeMills();
    // do somethind
    long end2 = System.currentTimeMills();
    System.out.println("某某1執(zhí)行耗時:" + (end -start));
    System.out.println("某某2執(zhí)行耗時:" + (end2 -start2));
}

如果改用stopWatch 實現(xiàn)的一個示例

public class StopWatchDemo {
    public static void main(String[] args) throws InterruptedException {
         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 someting
       Thread.sleep(200);
       sw.stop();
       System.out.println("sw.prettyPrint()-------");
       System.out.println(sw.prettyPrint());
    }
}

運行結果如下:

sw.prettyPrint()------
StopWatch 'test': running time (millis) = 310
-----------------------------------------
ms     %     Task name
-----------------------------------------
00110  035%  task1
00200  065%  task2

通過start 與stop 方法分別記錄開始時間與結束時間,其中在記錄結束時間的時候,會維護一個鏈表類型的taskList 屬性,從而時該類可記錄多個任務,最后的輸出頁僅僅是對之前的記錄信息做了一個統(tǒng)一的歸納輸出。

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;
        }
    }
}

從代碼上可以看出, 其原理為使用LinkList 來承接歷史任務,使用自身屬性來承接當前的狀態(tài),調用start 的時候初始化自身狀態(tài),使用stop 的時候來結束當前的狀態(tài)然后加入到LinkList中

到此這篇關于Java中StopWatch的使用詳解的文章就介紹到這了,更多相關Java StopWatch使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java線程池隊列DelayQueue的使用詳解

    Java線程池隊列DelayQueue的使用詳解

    這篇文章主要介紹了Java線程池隊列DelayQueue的使用詳解,DelayQueue顧名思義,它是個無邊界延遲隊列,它的底層是基于PriorityBlockingQueue實現(xiàn)的,該隊列中的元素都是按照過期時間順序排序的,隊列頭部放的是即將過期的元素,需要的朋友可以參考下
    2023-12-12
  • 使用maven war包打包去除jar包瘦身

    使用maven war包打包去除jar包瘦身

    這篇文章主要介紹了使用maven war包打包去除jar包瘦身操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • MyBatis Plus整合Redis實現(xiàn)分布式二級緩存的問題

    MyBatis Plus整合Redis實現(xiàn)分布式二級緩存的問題

    Mybatis內置的二級緩存在分布式環(huán)境下存在分布式問題,無法使用,但是我們可以整合Redis來實現(xiàn)分布式的二級緩存,這篇文章給大家介紹MyBatis Plus整合Redis實現(xiàn)分布式二級緩存,感興趣的朋友跟隨小編一起看看吧
    2023-11-11
  • java多線程之火車售票系統(tǒng)模擬實例

    java多線程之火車售票系統(tǒng)模擬實例

    下面小編就為大家?guī)硪黄猨ava多線程之火車售票系統(tǒng)模擬實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • Java中instanceof關鍵字的用法總結

    Java中instanceof關鍵字的用法總結

    instanceof是Java的一個二元操作符,和==,>,<是同一類東東。由于它是由字母組成的,所以也是Java的保留關鍵字。它的作用是測試它左邊的對象是否是它右邊的類的實例,返回boolean類型的數(shù)據(jù)
    2013-10-10
  • IDEA整合Dubbo+Zookeeper+SpringBoot實現(xiàn)

    IDEA整合Dubbo+Zookeeper+SpringBoot實現(xiàn)

    初學者,想自己動手做一個簡單的demo,本文主要介紹了IDEA整合Dubbo+Zookeeper+SpringBoot實現(xiàn),需要的朋友們下面隨著小編來一起學習學習吧
    2021-06-06
  • 詳解java實現(xiàn)簡單掃碼登錄功能(模仿微信網頁版掃碼)

    詳解java實現(xiàn)簡單掃碼登錄功能(模仿微信網頁版掃碼)

    這篇文章主要介紹了java實現(xiàn)簡單掃碼登錄功能(模仿微信網頁版掃碼),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-05-05
  • Java單例模式下的MongoDB數(shù)據(jù)庫操作工具類

    Java單例模式下的MongoDB數(shù)據(jù)庫操作工具類

    這篇文章主要介紹了Java單例模式下的MongoDB數(shù)據(jù)庫操作工具類,結合實例形式分析了java基于單例模式下操作MongoDB數(shù)據(jù)庫相關連接、查詢、插入、刪除等操作封裝技巧,需要的朋友可以參考下
    2018-01-01
  • 在Java中輕松將HTML格式文本轉換為純文本的方法示例(保留換行)

    在Java中輕松將HTML格式文本轉換為純文本的方法示例(保留換行)

    這篇文章主要介紹了在Java中輕松將HTML格式文本轉換為純文本的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-04-04
  • spring mail借助qq郵箱服務器發(fā)送郵件

    spring mail借助qq郵箱服務器發(fā)送郵件

    這篇文章主要介紹了spring mail借助qq郵箱服務器發(fā)送郵件的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-12-12

最新評論