最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring計(jì)時器stopwatch使用詳解

 更新時間:2021年08月12日 14:32:17   作者:一個不二  
這篇文章主要介紹了Spring計(jì)時器stopwatch使用詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

 StopWatch是位于org.springframework.util包下的一個工具類,通過它可方便的對程序部分代碼進(jìn)行計(jì)時(ms級別),適用于同步單線程代碼塊。
正常情況下,我們?nèi)绻枰茨扯未a的執(zhí)行耗時,會通過如下的方式進(jìn)行查看:

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));
}
運(yùn)行結(jié)果:
某某1執(zhí)行耗時:105
某某2執(zhí)行耗時:203

    該種方法通過獲取執(zhí)行完成時間與執(zhí)行開始時間的差值得到程序的執(zhí)行時間,簡單直接有效,但想必寫多了也是比較煩人的,尤其是碰到不可描述的代碼時,會更加的讓人忍不住多寫幾個bug聊表敬意,而且該結(jié)果也不夠直觀,此時會想是否有一個工具類,提供了這些方法,或者自己寫個工具類,剛好可以滿足這種場景,并且把結(jié)果更加直觀的展現(xiàn)出來。
首先我們的需求如下:

  1. 記錄開始時間點(diǎn)
  2. 記錄結(jié)束時間點(diǎn)
  3. 輸出執(zhí)行時間及各個時間段的占比

 根據(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());
}
運(yùn)行結(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í)行時間。
運(yùn)行代碼及結(jié)果:

System.out.println("sw.shortSummary()~~~~~~~~~~~~~~~~~");
System.out.println(sw.shortSummary());
System.out.println("sw.getTotalTimeMillis()~~~~~~~~~~~~~~~~~");
System.out.println(sw.getTotalTimeMillis());
運(yùn)行結(jié)果
sw.shortSummary()~~~~~~~~~~~~~~~~~
StopWatch 'test': running time (millis) = 308
sw.getTotalTimeMillis()~~~~~~~~~~~~~~~~~
308

 其實(shí)以上內(nèi)容在該工具類中實(shí)現(xiàn)也極其簡單,通過start與stop方法分別記錄開始時間與結(jié)束時間,其中在記錄結(jié)束時間時,會維護(hù)一個鏈表類型的tasklist屬性,從而使該類可記錄多個任務(wù),最后的輸出也僅僅是對之前記錄的信息做了一個統(tǒng)一的歸納輸出,從而使結(jié)果更加直觀的展示出來。
StopWatch優(yōu)缺點(diǎn):
優(yōu)點(diǎn):

  1. spring自帶工具類,可直接使用
  2. 代碼實(shí)現(xiàn)簡單,使用更簡單
  3. 統(tǒng)一歸納,展示每項(xiàng)任務(wù)耗時與占用總時間的百分比,展示結(jié)果直觀性能消耗相對較小,并且最大程度的保證了start與stop之間的時間記錄的準(zhǔn)確性
  4. 可在start時直接指定任務(wù)名字,從而更加直觀的顯示記錄結(jié)果

缺點(diǎn):

  1. 一個StopWatch實(shí)例一次只能開啟一個task,不能同時start多個task,并且在該task未stop之前不能start一個新的task,必須在該task stop之后才能開啟新的task,若要一次開啟多個,需要new不同的StopWatch實(shí)例
  2. 代碼侵入式使用,需要改動多處代碼

spring中StopWatch源碼實(shí)現(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;
        }
    }

}

到此這篇關(guān)于Spring計(jì)時器stopwatch使用詳解的文章就介紹到這了,更多相關(guān)Spring計(jì)時器stopwatch內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • idea插件無法下載4的種解決方式

    idea插件無法下載4的種解決方式

    這篇文章主要介紹了idea插件無法下載4的種解決方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • IDEA中配置文件格式為UTF-8的操作方法

    IDEA中配置文件格式為UTF-8的操作方法

    這篇文章主要介紹了IDEA中配置文件格式為UTF-8的操作方法,第一個需要設(shè)置文件編碼格式的位置,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-10-10
  • Java字符串拼接+和StringBuilder的比較與選擇

    Java字符串拼接+和StringBuilder的比較與選擇

    Java 提供了兩種主要的方式:使用 "+" 運(yùn)算符和使用 StringBuilder 類,本文主要介紹了Java字符串拼接+和StringBuilder的比較與選擇,感興趣的可以了解一下
    2023-10-10
  • IDEA設(shè)置字體隨鼠標(biāo)滾動放大縮小的實(shí)現(xiàn)

    IDEA設(shè)置字體隨鼠標(biāo)滾動放大縮小的實(shí)現(xiàn)

    這篇文章主要介紹了IDEA設(shè)置字體隨鼠標(biāo)滾動放大縮小的實(shí)現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Java使用poi操作excel實(shí)例解析

    Java使用poi操作excel實(shí)例解析

    這篇文章主要為大家詳細(xì)介紹了Java使用poi操作excel的簡單實(shí)例,感興趣的小伙伴們可以參考一下
    2016-05-05
  • springboot如何配置多kafka

    springboot如何配置多kafka

    這篇文章主要介紹了springboot如何配置多kafka問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • java生成mvt切片的方法實(shí)現(xiàn)

    java生成mvt切片的方法實(shí)現(xiàn)

    本文主要介紹了java生成mvt切片的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • 詳解WebSocket+spring示例demo(已使用sockJs庫)

    詳解WebSocket+spring示例demo(已使用sockJs庫)

    本篇文章主要介紹了WebSocket spring示例demo(已使用sockJs庫),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-01-01
  • 聊聊Spring循環(huán)依賴三級緩存是否可以減少為二級緩存的情況

    聊聊Spring循環(huán)依賴三級緩存是否可以減少為二級緩存的情況

    這篇文章主要介紹了聊聊Spring循環(huán)依賴三級緩存是否可以減少為二級緩存的情況,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Springboot @Value注入boolean設(shè)置默認(rèn)值方式

    Springboot @Value注入boolean設(shè)置默認(rèn)值方式

    這篇文章主要介紹了Springboot @Value注入boolean設(shè)置默認(rèn)值方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03

最新評論

凌云县| 颍上县| 汉沽区| 牙克石市| 屏南县| 循化| 温州市| 尤溪县| 深水埗区| 探索| 崇左市| 托克逊县| 黄浦区| 沂源县| 大名县| 商水县| 哈巴河县| 资溪县| 榕江县| 绥阳县| 平乡县| 靖安县| 唐海县| 曲周县| 靖远县| 青铜峡市| 花莲市| 南澳县| 军事| 扶绥县| 江安县| 小金县| 溧阳市| 遂宁市| 桓台县| 重庆市| 来宾市| 米林县| 清原| 电白县| 安化县|