StatisticsQpsInfo.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /// v3
  2. using System;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace CLClient.Statistics
  6. {
  7. public class StatisticsQpsInfo
  8. {
  9. //public static StatisQpsInfo Instance = new StatisQpsInfo();
  10. string name = "";
  11. DateTime? startTime;
  12. bool finished = false;
  13. public void Start(string name)
  14. {
  15. this.name += name;
  16. finished = false;
  17. startTime = DateTime.Now;
  18. Console.WriteLine("¿ªÊ¼");
  19. Task.Run(() =>
  20. {
  21. while (!finished)
  22. {
  23. Console.WriteLine(ToString());
  24. Thread.Sleep(1000);
  25. }
  26. });
  27. }
  28. public void Stop()
  29. {
  30. finished = true;
  31. Console.WriteLine("½áÊø");
  32. Console.WriteLine(ToString());
  33. }
  34. public int RequestCount = 0;
  35. public void IncrementRequest() => Interlocked.Increment(ref RequestCount);
  36. public long RequestTicks = 0;
  37. public void IncrementRequestTicks(long value) => Interlocked.Add(ref RequestTicks, value);
  38. public int ErrorCount = 0;
  39. public void IncrementError() => Interlocked.Increment(ref ErrorCount);
  40. long lastRequestTicks = 0;
  41. int lastCount = 0;
  42. DateTime lastTime;
  43. public override string ToString()
  44. {
  45. var curCount = RequestCount;
  46. var curRequestTicks = RequestTicks;
  47. var msg = $"[{name}]ReqCount: {curCount}";
  48. double d;
  49. if (curCount > 0)
  50. {
  51. d = ErrorCount * 100.0 / curCount;
  52. msg += $",error:{ErrorCount}({d.ToString("0.00")}%)";
  53. }
  54. if (startTime.HasValue)
  55. {
  56. if (lastCount == 0)
  57. {
  58. lastTime = startTime.Value;
  59. }
  60. var curTime = DateTime.Now;
  61. //sum
  62. var ms = (curTime - startTime.Value).TotalMilliseconds;
  63. d = curCount / ms * 1000;
  64. msg += $",qps:{d.ToString("0.00")}";
  65. ms = 1.0 * curRequestTicks / TimeSpan.TicksPerMillisecond;
  66. d = (curCount <= 0 ? 0 : ms / curCount);
  67. msg += $",ms/req:{d.ToString("0.00")}";
  68. //cur
  69. msg += $",------Cur";
  70. msg += $",ReqCount: {curCount}";
  71. ms = (curTime - lastTime).TotalMilliseconds;
  72. d = (curCount - lastCount) / ms * 1000;
  73. msg += $",qps:{d.ToString("0.00")}";
  74. ms = 1.0 * (curRequestTicks - lastRequestTicks) / TimeSpan.TicksPerMillisecond;
  75. d = (curCount <= lastCount ? 0 : ms / (curCount - lastCount));
  76. msg += $",ms/req:{d.ToString("0.00")}";
  77. lastRequestTicks = curRequestTicks;
  78. lastCount = curCount;
  79. lastTime = curTime;
  80. return msg;
  81. }
  82. return msg;
  83. }
  84. }
  85. }