task_duration_metric_reporter.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef COMPONENTS_SCHEDULING_METRICS_TASK_DURATION_METRIC_REPORTER_H_
  5. #define COMPONENTS_SCHEDULING_METRICS_TASK_DURATION_METRIC_REPORTER_H_
  6. #include <memory>
  7. #include "base/component_export.h"
  8. #include "base/metrics/histogram.h"
  9. #include "base/numerics/clamped_math.h"
  10. #include "base/time/time.h"
  11. namespace base {
  12. class HistogramBase;
  13. }
  14. namespace scheduling_metrics {
  15. // A helper class to report total task runtime split by the different types of
  16. // |TypeClass|. Only full seconds are reported. Note that partial seconds are
  17. // rounded up/down, so that on average the correct value is reported when many
  18. // reports are added.
  19. //
  20. // |TaskClass| is an enum which should have kClass field.
  21. template <class TaskClass>
  22. class TaskDurationMetricReporter {
  23. public:
  24. // Note that 1000*1000 is used to get microseconds precision.
  25. explicit TaskDurationMetricReporter(const char* metric_name)
  26. : value_per_type_histogram_(new base::ScaledLinearHistogram(
  27. metric_name,
  28. 1,
  29. static_cast<int>(TaskClass::kMaxValue) + 1,
  30. static_cast<int>(TaskClass::kMaxValue) + 2,
  31. 1000 * 1000,
  32. base::HistogramBase::kUmaTargetedHistogramFlag)) {}
  33. TaskDurationMetricReporter(const TaskDurationMetricReporter&) = delete;
  34. TaskDurationMetricReporter& operator=(const TaskDurationMetricReporter&) =
  35. delete;
  36. void RecordTask(TaskClass task_class, base::TimeDelta duration) {
  37. DCHECK_LT(static_cast<int>(task_class),
  38. static_cast<int>(TaskClass::kMaxValue) + 1);
  39. // To get microseconds precision, duration is converted to microseconds
  40. // since |value_per_type_histogram_| is constructed with a scale of
  41. // 1000*1000.
  42. const int task_micros =
  43. base::saturated_cast<int>(duration.InMicroseconds());
  44. if (task_micros > 0) {
  45. value_per_type_histogram_->AddScaledCount(static_cast<int>(task_class),
  46. task_micros);
  47. }
  48. }
  49. private:
  50. std::unique_ptr<base::ScaledLinearHistogram> value_per_type_histogram_;
  51. };
  52. } // namespace scheduling_metrics
  53. #endif // COMPONENTS_SCHEDULING_METRICS_TASK_DURATION_METRIC_REPORTER_H_