美文网首页
Android跟踪函数消耗时间

Android跟踪函数消耗时间

作者: hwhjxjs | 来源:发表于2020-04-20 06:45 被阅读0次
    public class TimeMonitorManager {
        private static final String TAG = "TimeMonitorManager";
    
        private HashMap<String, Long> mTimeTagMap = new HashMap<>();
        private long mStartTime = 0;
        private static volatile TimeMonitorManager mMonitorManager;
        
        private TimeMonitorManager() {
    
        }
    
        public static TimeMonitorManager getInstance() {
            if (mMonitorManager == null) {
                synchronized (TimeMonitorManager.class) {
                    if (mMonitorManager == null) {
                        mMonitorManager = new TimeMonitorManager();
                    }
                }
            }
            return mMonitorManager;
        }
    
        /**
         * 开始监听.
         */
        public void startMonitor() {
            if (mTimeTagMap.size() > 0) {
                mTimeTagMap.clear();
            }
    
            mStartTime = System.currentTimeMillis();
    
        }
    
    
        /**
         * 结束监听.
         * @param tag 所要打印的tag.
         */
        public void endMonitor(String tag) {
            if (mTimeTagMap.get(tag) != null) {
                mTimeTagMap.remove(tag);
            }
    
            long time = System.currentTimeMillis() - mStartTime;
            mTimeTagMap.put(tag, time);
            showData();
        }
    
        private void showData() {
            if (mTimeTagMap.size() <= 0) {
                return;
            }
    
            for (String tag: mTimeTagMap.keySet()
                 ) {
                long time = mTimeTagMap.get(tag);
                Log.d(TAG, tag + ": " + time);
            }
        }
    
    }
    

    用法举例

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            TimeMonitorManager.getInstance().startMonitor();
            setContentView(R.layout.activity_main);
            TimeMonitorManager.getInstance().endMonitor(TAG + " onCreate setContentView");
        }
    

    相关文章

      网友评论

          本文标题:Android跟踪函数消耗时间

          本文链接:https://www.haomeiwen.com/subject/ijyhihtx.html