SpeedStatistic.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef SPEED_STATISTIC_H_
  11. #define SPEED_STATISTIC_H_
  12. #include "TimeTicker.h"
  13. namespace toolkit {
  14. class BytesSpeed {
  15. public:
  16. BytesSpeed() = default;
  17. ~BytesSpeed() = default;
  18. /**
  19. * 添加统计字节
  20. */
  21. BytesSpeed &operator+=(size_t bytes) {
  22. _bytes += bytes;
  23. if (_bytes > 1024 * 1024) {
  24. //数据大于1MB就计算一次网速
  25. computeSpeed();
  26. }
  27. return *this;
  28. }
  29. /**
  30. * 获取速度,单位bytes/s
  31. */
  32. int getSpeed() {
  33. if (_ticker.elapsedTime() < 1000) {
  34. //获取频率小于1秒,那么返回上次计算结果
  35. return _speed;
  36. }
  37. return computeSpeed();
  38. }
  39. private:
  40. int computeSpeed() {
  41. auto elapsed = _ticker.elapsedTime();
  42. if (!elapsed) {
  43. return _speed;
  44. }
  45. _speed = (int)(_bytes * 1000 / elapsed);
  46. _ticker.resetTime();
  47. _bytes = 0;
  48. return _speed;
  49. }
  50. private:
  51. int _speed = 0;
  52. size_t _bytes = 0;
  53. Ticker _ticker;
  54. };
  55. } /* namespace toolkit */
  56. #endif /* SPEED_STATISTIC_H_ */