1 // Copyright 2016 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 
5 #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_THREAD_LOAD_TRACKER_H_
6 #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_THREAD_LOAD_TRACKER_H_
7 
8 #include "base/callback.h"
9 #include "base/macros.h"
10 #include "base/time/time.h"
11 #include "third_party/blink/renderer/platform/platform_export.h"
12 #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
13 
14 namespace blink {
15 namespace scheduler {
16 
17 // This class tracks thread load level, i.e. percentage of wall time spent
18 // running tasks.
19 // In order to avoid bias it reports load level at regular intervals.
20 // Every |reporting_interval_| time units, it reports the average thread load
21 // level computed using a sliding window of width |reporting_interval_|.
22 class PLATFORM_EXPORT ThreadLoadTracker {
23   DISALLOW_NEW();
24 
25  public:
26   // Callback is called with (current_time, load_level) parameters.
27   using Callback = base::RepeatingCallback<void(base::TimeTicks, double)>;
28 
29   ThreadLoadTracker(base::TimeTicks now,
30                     const Callback& callback,
31                     base::TimeDelta reporting_interval);
32   ~ThreadLoadTracker();
33 
34   void Pause(base::TimeTicks now);
35   void Resume(base::TimeTicks now);
36 
37   // Note: this does not change |thread_state_|.
38   void Reset(base::TimeTicks now);
39 
40   void RecordTaskTime(base::TimeTicks start_time, base::TimeTicks end_time);
41 
42   void RecordIdle(base::TimeTicks now);
43 
44   // TODO(altimin): Count wake-ups.
45 
46  private:
47   enum class ThreadState { kActive, kPaused };
48 
49   enum class TaskState { kTaskRunning, kIdle };
50 
51   // This function advances |time_| to |now|, calling |callback_|
52   // in the process (multiple times if needed).
53   void Advance(base::TimeTicks now, TaskState task_state);
54 
55   double Load();
56 
57   // |time_| is the last timestamp LoadTracker knows about.
58   base::TimeTicks time_;
59   base::TimeTicks next_reporting_time_;
60 
61   ThreadState thread_state_;
62   base::TimeTicks last_state_change_time_;
63 
64   base::TimeDelta reporting_interval_;
65 
66   // Recorded run time in window
67   // [next_reporting_time - reporting_interval, next_reporting_time].
68   base::TimeDelta run_time_inside_window_;
69 
70   Callback callback_;
71 };
72 
73 }  // namespace scheduler
74 }  // namespace blink
75 
76 #endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_THREAD_LOAD_TRACKER_H_
77