ray_microbenchmark_helpers.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import os
  2. import time
  3. from contextlib import contextmanager
  4. from typing import List, Optional, Tuple
  5. import numpy as np
  6. import ray
  7. # Only run tests matching this filter pattern.
  8. filter_pattern = os.environ.get("TESTS_TO_RUN", "")
  9. skip_pattern = os.environ.get("TESTS_TO_SKIP", "")
  10. def timeit(
  11. name, fn, multiplier=1, warmup_time_sec=10
  12. ) -> List[Optional[Tuple[str, float, float]]]:
  13. if filter_pattern and filter_pattern not in name:
  14. return [None]
  15. if skip_pattern and skip_pattern in name:
  16. return [None]
  17. # sleep for a while to avoid noisy neigbhors.
  18. # related issue: https://github.com/ray-project/ray/issues/22045
  19. time.sleep(warmup_time_sec)
  20. # warmup
  21. start = time.perf_counter()
  22. count = 0
  23. while time.perf_counter() - start < 1:
  24. fn()
  25. count += 1
  26. # real run
  27. step = count // 10 + 1
  28. stats = []
  29. for _ in range(4):
  30. start = time.perf_counter()
  31. count = 0
  32. while time.perf_counter() - start < 2:
  33. for _ in range(step):
  34. fn()
  35. count += step
  36. end = time.perf_counter()
  37. stats.append(multiplier * count / (end - start))
  38. mean = np.mean(stats)
  39. sd = np.std(stats)
  40. print(name, "per second", round(mean, 2), "+-", round(sd, 2))
  41. return [(name, mean, sd)]
  42. async def asyncio_timeit(
  43. name, async_fn, multiplier=1, warmup_time_sec=10
  44. ) -> List[Optional[Tuple[str, float, float]]]:
  45. if filter_pattern and filter_pattern not in name:
  46. return [None]
  47. if skip_pattern and skip_pattern in name:
  48. return [None]
  49. # sleep for a while to avoid noisy neigbhors.
  50. # related issue: https://github.com/ray-project/ray/issues/22045
  51. time.sleep(warmup_time_sec)
  52. # warmup
  53. start = time.perf_counter()
  54. count = 0
  55. while time.perf_counter() - start < 1:
  56. await async_fn()
  57. count += 1
  58. # real run
  59. step = count // 10 + 1
  60. stats = []
  61. for _ in range(4):
  62. start = time.perf_counter()
  63. count = 0
  64. while time.perf_counter() - start < 2:
  65. for _ in range(step):
  66. await async_fn()
  67. count += step
  68. end = time.perf_counter()
  69. stats.append(multiplier * count / (end - start))
  70. mean = np.mean(stats)
  71. sd = np.std(stats)
  72. print(name, "per second", round(mean, 2), "+-", round(sd, 2))
  73. return [(name, mean, sd)]
  74. @contextmanager
  75. def ray_setup_and_teardown(**init_args):
  76. ray.init(**init_args)
  77. try:
  78. yield None
  79. finally:
  80. ray.shutdown()