1// Copyright 2014 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#include "cc/debug/lap_timer.h"
6
7#include "base/logging.h"
8
9namespace cc {
10
11namespace {
12
13base::TimeTicks Now() {
14  return base::TimeTicks::IsThreadNowSupported()
15             ? base::TimeTicks::ThreadNow()
16             : base::TimeTicks::HighResNow();
17}
18
19}  // namespace
20
21LapTimer::LapTimer(int warmup_laps,
22                   base::TimeDelta time_limit,
23                   int check_interval)
24    : warmup_laps_(warmup_laps),
25      remaining_warmups_(0),
26      remaining_no_check_laps_(0),
27      time_limit_(time_limit),
28      check_interval_(check_interval) {
29  DCHECK_GT(check_interval, 0);
30  Reset();
31}
32
33void LapTimer::Reset() {
34  accumulator_ = base::TimeDelta();
35  num_laps_ = 0;
36  remaining_warmups_ = warmup_laps_;
37  remaining_no_check_laps_ = check_interval_;
38  Start();
39}
40
41void LapTimer::Start() {
42  start_time_ = Now();
43}
44
45bool LapTimer::IsWarmedUp() { return remaining_warmups_ <= 0; }
46
47void LapTimer::NextLap() {
48  if (!IsWarmedUp()) {
49    --remaining_warmups_;
50    if (IsWarmedUp()) {
51      Start();
52    }
53    return;
54  }
55  ++num_laps_;
56  --remaining_no_check_laps_;
57  if (!remaining_no_check_laps_) {
58    base::TimeTicks now = Now();
59    accumulator_ += now - start_time_;
60    start_time_ = now;
61    remaining_no_check_laps_ = check_interval_;
62  }
63}
64
65bool LapTimer::HasTimeLimitExpired() { return accumulator_ >= time_limit_; }
66
67bool LapTimer::HasTimedAllLaps() { return !(num_laps_ % check_interval_); }
68
69float LapTimer::MsPerLap() {
70  DCHECK(HasTimedAllLaps());
71  return accumulator_.InMillisecondsF() / num_laps_;
72}
73
74float LapTimer::LapsPerSecond() {
75  DCHECK(HasTimedAllLaps());
76  return num_laps_ / accumulator_.InSecondsF();
77}
78
79int LapTimer::NumLaps() { return num_laps_; }
80
81}  // namespace cc
82