task_switch_time_tracker.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2015 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 ASH_METRICS_TASK_SWITCH_TIME_TRACKER_H_
  5. #define ASH_METRICS_TASK_SWITCH_TIME_TRACKER_H_
  6. #include <memory>
  7. #include <string>
  8. #include "ash/ash_export.h"
  9. #include "base/time/time.h"
  10. namespace base {
  11. class HistogramBase;
  12. class TickClock;
  13. }
  14. namespace ash {
  15. // Tracks time deltas between task switches and records them in a histogram.
  16. class ASH_EXPORT TaskSwitchTimeTracker {
  17. public:
  18. // Create a TaskSwitchTimeTracker that will record data to the histogram with
  19. // the given |histogram_name|.
  20. explicit TaskSwitchTimeTracker(const std::string& histogram_name);
  21. TaskSwitchTimeTracker(const TaskSwitchTimeTracker&) = delete;
  22. TaskSwitchTimeTracker& operator=(const TaskSwitchTimeTracker&) = delete;
  23. ~TaskSwitchTimeTracker();
  24. // Notifies |this| that a task switch has occurred. A histogram data point
  25. // will be recorded for all calls but the first.
  26. void OnTaskSwitch();
  27. private:
  28. friend class TaskSwitchTimeTrackerTestAPI;
  29. // Private constructor that the TaskSwitchTimeTrackerTestAPI can use to
  30. // inject a custom |tick_clock|.
  31. // This doesn't take the ownership of the clock. |tick_clock| must outlive
  32. // TaskSwitchTimeTracker.
  33. TaskSwitchTimeTracker(const std::string& histogram_name,
  34. const base::TickClock* tick_clock);
  35. // Returns true if |last_action_time_| has a valid value.
  36. bool HasLastActionTime() const;
  37. // Sets the |last_action_time_| to |tick_clock_|'s current value and returns
  38. // the previous value for |last_action_time_|.
  39. base::TimeTicks SetLastActionTime();
  40. // Records a data point in the histogram.
  41. void RecordTimeDelta();
  42. // Lazily obtains and sets the |histogram_|.
  43. base::HistogramBase* GetHistogram();
  44. // The histogram name to record data to.
  45. std::string histogram_name_;
  46. // The histogram to log data to. Set via GetHistogram() using lazy load.
  47. base::HistogramBase* histogram_ = nullptr;
  48. // Tracks the last time OnTaskSwitch() was called. A value of
  49. // base::TimeTicks() should be interpreted as not set.
  50. base::TimeTicks last_action_time_ = base::TimeTicks();
  51. // The clock used to determine the |last_action_time_|.
  52. const base::TickClock* tick_clock_;
  53. };
  54. } // namespace ash
  55. #endif // ASH_METRICS_TASK_SWITCH_TIME_TRACKER_H_