using System; using System.Collections.Generic; using System.Diagnostics; namespace LJLib.D { public static class DebugHelper { private static Dictionary _watchs = null; private static Dictionary _counters = null; private static int cnt = 0; private static Dictionary watchs { get { if (_watchs == null) { _watchs = new Dictionary(); } return _watchs; } } private static Dictionary Counters { get { if (_counters == null) { _counters = new Dictionary(); } return _counters; } } private static Stopwatch GetWatch(string key) { if (!watchs.ContainsKey(key)) { watchs[key] = new Stopwatch(); } return watchs[key]; } #region 公共方法 [Conditional("DEBUG")] public static void Start(string key) { var counters = Counters; if (!counters.ContainsKey(key)) { counters[key] = 1; } else { counters[key] += 1; } var watch = GetWatch(key); watch.Start(); } [Conditional("DEBUG")] public static void Stop(string key) { var watch = GetWatch(key); watch.Stop(); } [Conditional("DEBUG")] public static void PrintAll() { string msg = string.Empty; PrintAll(ref msg); Debug.Write(msg); } [Conditional("DEBUG")] public static void PrintAll(ref string msg) { msg = "DEBUG TIMER:"; if (_watchs != null) { foreach (var watch in _watchs) { if (string.IsNullOrEmpty(msg)) { msg = string.Empty; } else { msg += "\r\n"; } if (Counters.ContainsKey(watch.Key)) { msg += string.Format("{0}:{1:#,##0.##} / {2} = {3}", watch.Key, watch.Value.Elapsed.TotalSeconds, Counters[watch.Key], watch.Value.Elapsed.TotalSeconds/Counters[watch.Key]); } } _watchs.Clear(); _counters.Clear(); } } [Conditional("DEBUG")] public static void Reset() { cnt = 0; } [Conditional("DEBUG")] public static void Inc() { cnt++; //if (cnt % 1000 == 0) //{ // Debug.Write(string.Format("inc:{0}", cnt)); //} if (cnt >= 1000000) { Debug.Write("可能出现了死循环"); throw new Exception("可能出现了死循环"); } } #endregion } }