您现在的位置是:首页 > 文章详情

Java统计代码段的执行时间

日期:2018-05-02点击:503
版权声明:欢迎评论和转载,转载请注明来源。 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 




原文链接:https://yq.aliyun.com/articles/657863
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章