metrics_example.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import time
  2. import ray
  3. from ray.util.metrics import Counter, Gauge, Histogram
  4. ray.init(_metrics_export_port=8080)
  5. @ray.remote
  6. class MyActor:
  7. def __init__(self, name):
  8. self._curr_count = 0
  9. self.counter = Counter(
  10. "num_requests",
  11. description="Number of requests processed by the actor.",
  12. tag_keys=("actor_name", ))
  13. self.counter.set_default_tags({"actor_name": name})
  14. self.gauge = Gauge(
  15. "curr_count",
  16. description="Current count held by the actor. Goes up and down.",
  17. tag_keys=("actor_name", ))
  18. self.gauge.set_default_tags({"actor_name": name})
  19. self.histogram = Histogram(
  20. "request_latency",
  21. description="Latencies of requests in ms.",
  22. boundaries=[0.1, 1],
  23. tag_keys=("actor_name", ))
  24. self.histogram.set_default_tags({"actor_name": name})
  25. def process_request(self, num):
  26. start = time.time()
  27. self._curr_count += num
  28. # Increment the total request count.
  29. self.counter.inc()
  30. # Update the gauge to the new value.
  31. self.gauge.set(self._curr_count)
  32. # Record the latency for this request in ms.
  33. self.histogram.observe(1000 * (time.time() - start))
  34. return self._curr_count
  35. print("Starting actor.")
  36. my_actor = MyActor.remote("my_actor")
  37. print("Calling actor.")
  38. my_actor.process_request.remote(-10)
  39. print("Calling actor.")
  40. my_actor.process_request.remote(5)
  41. print("Metrics should be exported.")
  42. print("See http://localhost:8080 (this may take a few seconds to load).")
  43. # Sleep so we can look at the metrics before exiting.
  44. time.sleep(30)
  45. print("Exiting!")