利用threadlocal进行性能监控

public class Monitor {

    private static ThreadLocal<LinkedHashMap<String, Long>> monitorInfo = new ThreadLocal<>();

    public static void set(String step, Long cost) {
        LinkedHashMap<String, Long> map = monitorInfo.get();
        if (map == null) {
            map = new LinkedHashMap<String, Long>();
            monitorInfo.set(map);
        }
        monitorInfo.get().put(step, cost);
    }

    public static String toxString() {
        Set<Entry<String, Long>> entrySet = monitorInfo.get().entrySet();
        StringBuilder sb = new StringBuilder();
        long preCost = 0;
        Long start = monitorInfo.get().get("start");
        Long end = monitorInfo.get().get("end");
        sb.append(" [ total:" + (end - start) + " ms ] \n");
        for (Entry<String, Long> entry : entrySet) {
            sb.append(" [ " + entry.getKey() + " : " + (entry.getValue() - preCost) + " ms ] \n");
            preCost = entry.getValue();
        }
        return sb.toString();
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容