benchmark.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #pragma once
  2. #include "prometheus/metric.h"
  3. #include "prometheus/family.h"
  4. #include <chrono>
  5. namespace prometheus {
  6. class Benchmark : public Metric {
  7. #ifndef NDEBUG
  8. bool already_started = false;
  9. #endif
  10. std::chrono::time_point<std::chrono::high_resolution_clock> start_;
  11. std::chrono::time_point<std::chrono::high_resolution_clock>::duration elapsed = std::chrono::time_point<std::chrono::high_resolution_clock>::duration::zero(); // elapsed time
  12. public:
  13. using Value = double;
  14. using Family = CustomFamily<Benchmark>;
  15. static const Metric::Type static_type = Metric::Type::Counter;
  16. Benchmark() : Metric(Metric::Type::Counter) {}
  17. void start() {
  18. #ifndef NDEBUG
  19. if (already_started)
  20. throw std::runtime_error("try to start already started counter");
  21. else
  22. already_started = true;
  23. #endif
  24. start_ = std::chrono::high_resolution_clock::now();
  25. }
  26. void stop() {
  27. #ifndef NDEBUG
  28. if (already_started == false)
  29. throw std::runtime_error("try to stop already stoped counter");
  30. #endif
  31. std::chrono::time_point<std::chrono::high_resolution_clock> stop;
  32. stop = std::chrono::high_resolution_clock::now();
  33. elapsed += stop - start_;
  34. #ifndef NDEBUG
  35. already_started = false;
  36. #endif
  37. }
  38. double Get() const {
  39. return std::chrono::duration_cast<std::chrono::duration<double>>(elapsed).count();
  40. }
  41. virtual ClientMetric Collect() const {
  42. ClientMetric metric;
  43. metric.counter.value = Get();
  44. return metric;
  45. }
  46. };
  47. } // namespace prometheus