天天看點

Java統計代碼段的執行時間

版權聲明:歡迎評論和轉載,轉載請注明來源。 https://blog.csdn.net/zy332719794/article/details/80180571

通常在進行代碼測試和代碼優化的時候,會想要知道代碼執行時每段代碼的執行時間,以便進行代碼優化和調整。

下面封裝的類是利用代碼段标記和執行時間差進行統計。使用時,僅需要在代碼段中加入CodeTimer.set("标記");就可以了,列印 時調用CodeTimer.print();統計字段有代碼段、總時間(納秒)、執行次數、平均時間。

封裝類:

/**
 * 統計代碼段執行時間。
 * 在需要進行統計的代碼段調用CodeTimer.set()方法進行标記。
 * 列印時調用CodeTimer.print()方法
 */
public class CodeTimer {
    private static String lastMark = "start";
    private static long lastTime = System.nanoTime();
    private static final Map<String, Long> timeMap = new LinkedHashMap<String, Long>();
    private static final Map<String, Long> timeHappenCount = new LinkedHashMap<String, Long>();

    public static void set(int mark) {
        set("" + mark);
    };

    public static void set(String mark) {
        long thisTime = System.nanoTime();
        String key = "[" + lastMark + "]->[" + mark + "]";
        Long lastSummary = timeMap.get(key);
        if (lastSummary == null)
            lastSummary = 0L;

        timeMap.put(key, System.nanoTime() - lastTime + lastSummary);
        Long lastCount = timeHappenCount.get(key);
        if (lastCount == null)
            lastCount = 0L;

        timeHappenCount.put(key, ++lastCount);
        lastTime = thisTime;
        lastMark = mark;
    };

    public static void print() {
        Integer a = 0;
        System.out.println(
                String.format("%25s %18s %18s %18s",
                    "PROCESS", "TOTAL_TIME", "REPEAT_TIMES", "AVG_TIME"));
        for (Entry<String, Long> entry : timeMap.entrySet()) {
            System.out.println(
                String.format("%25s %18s %18s %18s", entry.getKey(),
                    String.format("%,d", entry.getValue()), timeHappenCount.get(entry.getKey()),
                    String.format("%,d", entry.getValue() / timeHappenCount.get(entry.getKey()))));
        }
    }
}           

列印出的效果形如:

PROCESS         TOTAL_TIME       REPEAT_TIMES           AVG_TIME
             [start]->[0]            152,312                  1            152,312
                 [0]->[4]         12,223,365                  1         12,223,365
                [4]->[10]            101,838                  6             16,973
                [10]->[8]          1,246,189                 34             36,652
                 [8]->[5]        489,096,299                 34         14,385,185
                 [5]->[6]        122,247,497                 34          3,595,514
                 [6]->[7]      2,686,057,029                 34         79,001,677
                 [7]->[1]             22,334                  1             22,334
                 [1]->[9]            911,191                  1            911,191