profiler.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
  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 os
  15. from contextlib import contextmanager
  16. from functools import wraps
  17. from paddle.framework import core
  18. _event_level = int(os.environ.get("EVENT_LEVEL", "0"))
  19. class SotProfiler:
  20. def __enter__(self):
  21. self.enable()
  22. def __exit__(self, exc_type, exc_val, exc_tb):
  23. self.disable()
  24. def enable(self, tag=None):
  25. core.nvprof_start()
  26. core.nvprof_enable_record_event()
  27. def disable(self):
  28. core.nvprof_stop()
  29. @contextmanager
  30. def EventGuard(event_name, event_level=1):
  31. try:
  32. global _event_level
  33. need_pop = False
  34. if _event_level >= event_level:
  35. core.nvprof_nvtx_push(event_name)
  36. need_pop = True
  37. yield
  38. finally:
  39. if need_pop:
  40. core.nvprof_nvtx_pop()
  41. def event_register(event_name, event_level=1):
  42. def event_wrapper(func):
  43. @wraps(func)
  44. def call_with_event(*args, **kwargs):
  45. with EventGuard(event_name, event_level=event_level):
  46. return func(*args, **kwargs)
  47. return call_with_event
  48. def do_nothing(func):
  49. return func
  50. global _event_level
  51. if _event_level >= event_level:
  52. return event_wrapper
  53. else:
  54. return do_nothing