Timer.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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> minTimes = new Dictionary<string, double>();
  13. private static Dictionary<String, double> maxTimes = new Dictionary<string, double>();
  14. private static Dictionary<String, double> sumTimes = new Dictionary<string, double>();
  15. private static Dictionary<String, int> numTimes = new Dictionary<string, int>();
  16. public static void start(String name) {
  17. if (!stopwatches.ContainsKey(name))
  18. {
  19. stopwatches.Add(name, new Stopwatch());
  20. minTimes.Add(name, int.MaxValue);
  21. maxTimes.Add(name, 0);
  22. sumTimes.Add(name, 0);
  23. numTimes.Add(name, 0);
  24. }
  25. stopwatches[name].Restart();
  26. }
  27. public static void stop(String name) {
  28. stopwatches[name].Stop();
  29. double time = Math.Round((double)stopwatches[name].ElapsedTicks / (double)Stopwatch.Frequency * 1000.0, 2);
  30. if (time < minTimes[name]) minTimes[name] = time;
  31. if (time > maxTimes[name]) maxTimes[name] = time;
  32. sumTimes[name] += time;
  33. numTimes[name]++;
  34. }
  35. public static void output(String name) {
  36. Logger.log(String.Format("name:{0}\tavg:{1:00.00}\tmin:{2:00.00}\tmax:{3:00.00}",
  37. name, sumTimes[name] / Math.Max(numTimes[name], 1), minTimes[name], maxTimes[name]), LogSubject.Timer);
  38. }
  39. public static void outputAll()
  40. {
  41. Logger.clear(LogSubject.Timer);
  42. Logger.log("---TIMERS-START---", LogSubject.Timer);
  43. foreach (String name in stopwatches.Keys) {
  44. output(name);
  45. }
  46. Logger.log("---TIMERS-END---", LogSubject.Timer);
  47. }
  48. }
  49. }