DebugHelper.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. namespace LJLib.D
  5. {
  6. public static class DebugHelper
  7. {
  8. private static Dictionary<string, Stopwatch> _watchs = null;
  9. private static Dictionary<string, int> _counters = null;
  10. private static int cnt = 0;
  11. private static Dictionary<string, Stopwatch> watchs
  12. {
  13. get
  14. {
  15. if (_watchs == null)
  16. {
  17. _watchs = new Dictionary<string, Stopwatch>();
  18. }
  19. return _watchs;
  20. }
  21. }
  22. private static Dictionary<string, int> Counters
  23. {
  24. get
  25. {
  26. if (_counters == null)
  27. {
  28. _counters = new Dictionary<string, int>();
  29. }
  30. return _counters;
  31. }
  32. }
  33. private static Stopwatch GetWatch(string key)
  34. {
  35. if (!watchs.ContainsKey(key))
  36. {
  37. watchs[key] = new Stopwatch();
  38. }
  39. return watchs[key];
  40. }
  41. #region 公共方法
  42. [Conditional("DEBUG")]
  43. public static void Start(string key)
  44. {
  45. var counters = Counters;
  46. if (!counters.ContainsKey(key))
  47. {
  48. counters[key] = 1;
  49. }
  50. else
  51. {
  52. counters[key] += 1;
  53. }
  54. var watch = GetWatch(key);
  55. watch.Start();
  56. }
  57. [Conditional("DEBUG")]
  58. public static void Stop(string key)
  59. {
  60. var watch = GetWatch(key);
  61. watch.Stop();
  62. }
  63. [Conditional("DEBUG")]
  64. public static void PrintAll()
  65. {
  66. string msg = string.Empty;
  67. PrintAll(ref msg);
  68. Debug.Write(msg);
  69. }
  70. [Conditional("DEBUG")]
  71. public static void PrintAll(ref string msg)
  72. {
  73. msg = "DEBUG TIMER:";
  74. if (_watchs != null)
  75. {
  76. foreach (var watch in _watchs)
  77. {
  78. if (string.IsNullOrEmpty(msg))
  79. {
  80. msg = string.Empty;
  81. }
  82. else
  83. {
  84. msg += "\r\n";
  85. }
  86. if (Counters.ContainsKey(watch.Key))
  87. {
  88. msg += string.Format("{0}:{1:#,##0.##} / {2} = {3}", watch.Key, watch.Value.Elapsed.TotalSeconds,
  89. Counters[watch.Key], watch.Value.Elapsed.TotalSeconds/Counters[watch.Key]);
  90. }
  91. }
  92. _watchs.Clear();
  93. _counters.Clear();
  94. }
  95. }
  96. [Conditional("DEBUG")]
  97. public static void Reset()
  98. {
  99. cnt = 0;
  100. }
  101. [Conditional("DEBUG")]
  102. public static void Inc()
  103. {
  104. cnt++;
  105. //if (cnt % 1000 == 0)
  106. //{
  107. // Debug.Write(string.Format("inc:{0}", cnt));
  108. //}
  109. if (cnt >= 1000000)
  110. {
  111. Debug.Write("可能出现了死循环");
  112. throw new Exception("可能出现了死循环");
  113. }
  114. }
  115. #endregion
  116. }
  117. }