1 // Copyright 2018 The Fuchsia 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 #pragma once
6 
7 #include <cobalt-client/cpp/histogram.h>
8 #include <lib/fzl/time.h>
9 #include <lib/zx/time.h>
10 #include <zircon/assert.h>
11 
12 namespace cobalt_client {
13 namespace internal {
14 
15 template <typename Clock> class TimerBase {
16 public:
TimerBase(bool is_collecting)17     explicit TimerBase(bool is_collecting) : start_(is_collecting ? Clock::now().get() : 0) {}
18     TimerBase(const TimerBase&) = delete;
TimerBase(TimerBase && other)19     TimerBase(TimerBase&& other) : start_(other.start_) { other.start_ = zx::ticks(0); }
20     TimerBase& operator=(const TimerBase&) = delete;
21     TimerBase& operator=(TimerBase&& other) = delete;
22     ~TimerBase() = default;
23 
24     // Returns the duration since creation. If |is_collecting| is false, will return
25     // 0.
End()26     zx::duration End() {
27         if (start_.get() == 0) {
28             return zx::duration(0);
29         }
30         return fzl::TicksToNs(Clock::now() - start_);
31     }
32 
33     // Resets the timer. If |is_collecting| is false, has no effect.
Reset()34     void Reset() {
35         if (start_.get() == 0) {
36             return;
37         }
38         start_ = Clock::now();
39     }
40 
41 private:
42     zx::ticks start_;
43 };
44 } // namespace internal
45 
46 // Utility class for measuring the amount of ticks in an interval.
47 //
48 // This class is moveable, but not copyable or assignable.
49 using Timer = internal::TimerBase<zx::ticks>;
50 
51 } // namespace cobalt_client
52