Skip to the code
+10 XP

#284 Rolling Average Frame Time

easy

A performance overlay shows the average of the last size frame times. Write a class FrameAverage:

  • new FrameAverage(size) sets the window size.
  • next(ms) records a frame time and returns the average of the last size recorded frame times, or of all of them if fewer than size have been recorded.

Each call must be O(1): don't re-add the whole window. Answers within 1e-5 of the exact average are accepted.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new FrameAverage(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["FrameAverage","next","next","next","next"]
[[3],[1],[10],[3],[5]]
Output: [null,1,5.5,4.666666666666667,6]

1, then (1 + 10) / 2, then (1 + 10 + 3) / 3, then (10 + 3 + 5) / 3 once 1 falls out.

Example 2

Input: ["FrameAverage","next","next"]
[[1],[16],[33]]
Output: [null,16,33]

With a window of 1, the average is the latest frame.

Constraints

  • 1 <= size <= 10^5
  • 0 <= ms <= 10^5
  • At most 3 * 10^5 calls.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).