通常在进行代码测试和代码优化的时候,会想要知道代码执行时每段代码的执行时间,以便进行代码优化和调整。
下面封装的类是利用代码段标记和执行时间差进行统计。使用时,仅需要在代码段中加入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 timeMap = new LinkedHashMap();
private static final Map timeHappenCount = new LinkedHashMap();
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 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