Timer.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace bbiwarg.Utility
  8. {
  9. class Timer
  10. {
  11. private static Dictionary<String, Stopwatch> stopwatches = new Dictionary<string, Stopwatch>();
  12. private static Dictionary<String, double> currentTimes = new Dictionary<string, double>();
  13. private static Dictionary<String, double> minTimes = new Dictionary<string, double>();
  14. private static Dictionary<String, double> maxTimes = new Dictionary<string, double>();
  15. private static Dictionary<String, double> sumTimes = new Dictionary<string, double>();
  16. private static Dictionary<String, int> numTimes = new Dictionary<string, int>();
  17. public static void start(String name)
  18. {
  19. if (!stopwatches.ContainsKey(name))
  20. {
  21. stopwatches.Add(name, new Stopwatch());
  22. minTimes.Add(name, int.MaxValue);
  23. maxTimes.Add(name, 0);
  24. sumTimes.Add(name, 0);
  25. numTimes.Add(name, 0);
  26. currentTimes.Add(name, 0);
  27. }
  28. stopwatches[name].Restart();
  29. }
  30. public static void stop(String name)
  31. {
  32. stopwatches[name].Stop();
  33. double time = Math.Round((double)stopwatches[name].ElapsedTicks / (double)Stopwatch.Frequency * 1000.0, 2);
  34. if (time < minTimes[name]) minTimes[name] = time;
  35. if (time > maxTimes[name]) maxTimes[name] = time;
  36. sumTimes[name] += time;
  37. numTimes[name]++;
  38. currentTimes[name] = time;
  39. }
  40. public static void output(String name)
  41. {
  42. Logger.log(String.Format("name:{0}\tavg:{1:00.00}\tcurrent:{2:00.00}",
  43. name, sumTimes[name] / Math.Max(numTimes[name], 1), currentTimes[name]), LogSubject.Timer);
  44. }
  45. public static void outputAll()
  46. {
  47. Logger.log("---TIMERS-START---", LogSubject.Timer);
  48. foreach (String name in stopwatches.Keys)
  49. {
  50. output(name);
  51. }
  52. Logger.log("---TIMERS-END---", LogSubject.Timer);
  53. }
  54. }
  55. }