Timer.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. namespace bbiwarg.Utility
  8. {
  9. class Timer
  10. {
  11. private static Object sync = new object();
  12. private static Dictionary<String, Stopwatch> stopwatches = new Dictionary<string, Stopwatch>();
  13. private static Dictionary<String, double> currentTimes = new Dictionary<string, double>();
  14. private static Dictionary<String, double> minTimes = new Dictionary<string, double>();
  15. private static Dictionary<String, double> maxTimes = new Dictionary<string, double>();
  16. private static Dictionary<String, double> sumTimes = new Dictionary<string, double>();
  17. private static Dictionary<String, int> numTimes = new Dictionary<string, int>();
  18. private static int maxNameLength = 1;
  19. public static void start(String name)
  20. {
  21. lock (sync)
  22. {
  23. if (!stopwatches.ContainsKey(name))
  24. {
  25. stopwatches.Add(name, new Stopwatch());
  26. minTimes.Add(name, int.MaxValue);
  27. maxTimes.Add(name, 0);
  28. sumTimes.Add(name, 0);
  29. numTimes.Add(name, 0);
  30. currentTimes.Add(name, 0);
  31. maxNameLength = Math.Max(maxNameLength, name.Length);
  32. }
  33. stopwatches[name].Restart();
  34. }
  35. }
  36. public static void stop(String name)
  37. {
  38. lock (sync)
  39. {
  40. stopwatches[name].Stop();
  41. double time = Math.Round((double)stopwatches[name].ElapsedTicks / (double)Stopwatch.Frequency * 1000.0, 2);
  42. if (time < minTimes[name]) minTimes[name] = time;
  43. if (time > maxTimes[name]) maxTimes[name] = time;
  44. sumTimes[name] += time;
  45. numTimes[name]++;
  46. currentTimes[name] = time;
  47. }
  48. }
  49. public static void outputAll()
  50. {
  51. lock (sync)
  52. {
  53. StringBuilder divider = new StringBuilder();
  54. divider.Append("├-");
  55. divider.Append(new String('-', maxNameLength));
  56. divider.Append("-┼-------┼-------┤");
  57. Console.Clear();
  58. Console.WriteLine(String.Format("| {0,-" + maxNameLength + "} | {1,-5} | {2,-5} |", "NAME", "AVG.", "CUR."));
  59. Console.WriteLine(divider.ToString());
  60. foreach (String name in stopwatches.Keys)
  61. {
  62. double average = sumTimes[name] / Math.Max(numTimes[name], 1);
  63. double current = currentTimes[name];
  64. Console.WriteLine(String.Format("| {0,-" + maxNameLength + "} | {1:00.00} | {2:00.00} |", name, average, current));
  65. }
  66. }
  67. }
  68. }
  69. }