Timer.cs 2.2 KB

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