benchmark.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import functools
  15. from types import GeneratorType
  16. import time
  17. import numpy as np
  18. from prettytable import PrettyTable
  19. from ...utils.flags import INFER_BENCHMARK_OUTPUT
  20. from ...utils import logging
  21. class Benchmark:
  22. def __init__(self, components):
  23. self._components = components
  24. self._e2e_tic = None
  25. self._e2e_elapse = None
  26. def reset(self):
  27. for name in self._components:
  28. cmp = self._components[name]
  29. cmp.timer.reset()
  30. self._e2e_tic = time.time()
  31. def gather(self, e2e_num):
  32. # lazy import for avoiding circular import
  33. from ..components.paddle_predictor import BasePaddlePredictor
  34. detail = []
  35. summary = {"preprocess": 0, "inference": 0, "postprocess": 0}
  36. op_tag = "preprocess"
  37. for name in self._components:
  38. cmp = self._components[name]
  39. times = cmp.timer.logs
  40. counts = len(times)
  41. avg = np.mean(times)
  42. total = np.sum(times)
  43. detail.append((name, counts, avg))
  44. if isinstance(cmp, BasePaddlePredictor):
  45. summary["inference"] += total
  46. op_tag = "postprocess"
  47. else:
  48. summary[op_tag] += total
  49. summary = [
  50. ("PreProcess", e2e_num, summary["preprocess"] / e2e_num),
  51. ("Inference", e2e_num, summary["inference"] / e2e_num),
  52. ("PostProcess", e2e_num, summary["postprocess"] / e2e_num),
  53. ("End2End", e2e_num, self._e2e_elapse / e2e_num),
  54. ]
  55. return detail, summary
  56. def collect(self, e2e_num):
  57. self._e2e_elapse = time.time() - self._e2e_tic
  58. detail, summary = self.gather(e2e_num)
  59. table = PrettyTable(["Component", "Call Counts", "Avg Time Per Call (ms)"])
  60. table.add_rows(
  61. [(name, cnts, f"{avg * 1000:.8f}") for name, cnts, avg in detail]
  62. )
  63. logging.info(table)
  64. table = PrettyTable(["Stage", "Num of Instances", "Avg Time Per Instance (ms)"])
  65. table.add_rows(
  66. [(name, cnts, f"{avg * 1000:.8f}") for name, cnts, avg in summary]
  67. )
  68. logging.info(table)
  69. if INFER_BENCHMARK_OUTPUT:
  70. str_ = "Component, Call Counts, Avg Time Per Call (ms)\n"
  71. str_ += "\n".join(
  72. [f"{name}, {cnts}, {avg * 1000:.18f}" for name, cnts, avg in detail]
  73. )
  74. str_ += "\n" + "*" * 100 + "\n"
  75. str_ += "Stage, Num of Instances, Avg Time Per Instance (ms)\n"
  76. str_ += "\n".join(
  77. [f"{name}, {cnts}, {avg * 1000:.18f}" for name, cnts, avg in summary]
  78. )
  79. with open(INFER_BENCHMARK_OUTPUT, "w") as f:
  80. f.write(str_)
  81. class Timer:
  82. def __init__(self):
  83. self._tic = None
  84. self._elapses = []
  85. def watch_func(self, func):
  86. @functools.wraps(func)
  87. def wrapper(*args, **kwargs):
  88. tic = time.time()
  89. output = func(*args, **kwargs)
  90. if isinstance(output, GeneratorType):
  91. return self.watch_generator(output)
  92. else:
  93. self._update(time.time() - tic)
  94. return output
  95. return wrapper
  96. def watch_generator(self, generator):
  97. @functools.wraps(generator)
  98. def wrapper():
  99. while 1:
  100. try:
  101. tic = time.time()
  102. item = next(generator)
  103. self._update(time.time() - tic)
  104. yield item
  105. except StopIteration:
  106. break
  107. return wrapper()
  108. def reset(self):
  109. self._tic = None
  110. self._elapses = []
  111. def _update(self, elapse):
  112. self._elapses.append(elapse)
  113. @property
  114. def logs(self):
  115. return self._elapses