1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #if !defined(InputEventStatistics_h_)
8 # define InputEventStatistics_h_
10 # include "mozilla/TimeStamp.h"
11 # include "mozilla/UniquePtr.h"
12 # include "nsTArray.h"
16 class InputEventStatistics
{
17 // The default amount of time (milliseconds) required for handling a input
19 static const uint16_t sDefaultInputDuration
= 1;
21 // The number of processed input events we use to predict the amount of time
22 // required to process the following input events.
23 static const uint16_t sInputCountForPrediction
= 9;
25 // The default maximum and minimum time (milliseconds) we reserve for handling
26 // input events in each frame.
27 static const uint16_t sMaxReservedTimeForHandlingInput
= 8;
28 static const uint16_t sMinReservedTimeForHandlingInput
= 1;
30 class TimeDurationCircularBuffer
{
32 int16_t mCurrentIndex
;
33 nsTArray
<TimeDuration
> mBuffer
;
37 TimeDurationCircularBuffer(uint32_t aSize
, TimeDuration
& aDefaultValue
)
38 : mSize(aSize
), mCurrentIndex(0) {
39 mSize
= mSize
== 0 ? sInputCountForPrediction
: mSize
;
40 for (int16_t index
= 0; index
< mSize
; ++index
) {
41 mBuffer
.AppendElement(aDefaultValue
);
42 mTotal
+= aDefaultValue
;
46 void Insert(TimeDuration
& aDuration
) {
47 mTotal
+= (aDuration
- mBuffer
[mCurrentIndex
]);
48 mBuffer
[mCurrentIndex
++] = aDuration
;
49 if (mCurrentIndex
== mSize
) {
54 TimeDuration
GetMean();
57 UniquePtr
<TimeDurationCircularBuffer
> mLastInputDurations
;
58 TimeDuration mMaxInputDuration
;
59 TimeDuration mMinInputDuration
;
62 // We'd like to have our constructor and destructor be private to enforce our
63 // singleton, but because UniquePtr needs to be able to destruct our class we
64 // can't. This is a trick that ensures that we're the only code that can
65 // construct ourselves: nobody else can access ConstructorCookie and therefore
66 // nobody else can construct an InputEventStatistics.
67 struct ConstructorCookie
{};
70 explicit InputEventStatistics(ConstructorCookie
&&);
71 ~InputEventStatistics() = default;
73 static InputEventStatistics
& Get();
75 void UpdateInputDuration(TimeDuration aDuration
) {
79 mLastInputDurations
->Insert(aDuration
);
82 TimeStamp
GetInputHandlingStartTime(uint32_t aInputCount
);
83 TimeDuration
GetMaxInputHandlingDuration() const;
85 void SetEnable(bool aEnable
) { mEnable
= aEnable
; }
88 class MOZ_RAII AutoTimeDurationHelper final
{
90 AutoTimeDurationHelper() { mStartTime
= TimeStamp::Now(); }
92 ~AutoTimeDurationHelper() {
93 InputEventStatistics::Get().UpdateInputDuration(TimeStamp::Now() -
101 } // namespace mozilla
103 #endif // InputEventStatistics_h_