summaryrefslogtreecommitdiffstats
path: root/xbmc/utils/Stopwatch.h
blob: 9ec2983b0bf4aec0b25c506fcc6bc4cbd6373d9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
 *  Copyright (C) 2005-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#pragma once

#include <chrono>
#include <stdint.h>

class CStopWatch
{
public:
  CStopWatch() = default;
  ~CStopWatch() = default;

  /*!
    \brief Retrieve the running state of the stopwatch.

    \return True if stopwatch has been started but not stopped.
  */
  inline bool IsRunning() const
  {
    return m_isRunning;
  }

  /*!
    \brief Record start time and change state to running.
  */
  inline void StartZero()
  {
    m_startTick = std::chrono::steady_clock::now();
    m_isRunning = true;
  }

  /*!
    \brief Record start time and change state to running, only if the stopwatch is stopped.
  */
  inline void Start()
  {
    if (!m_isRunning)
      StartZero();
  }

  /*!
    \brief Record stop time and change state to not running.
  */
  inline void Stop()
  {
    if(m_isRunning)
    {
      m_stopTick = std::chrono::steady_clock::now();
      m_isRunning = false;
    }
  }

  /*!
    \brief Set the start time such that time elapsed is now zero.
  */
  void Reset()
  {
    if (m_isRunning)
      m_startTick = std::chrono::steady_clock::now();
    else
      m_startTick = m_stopTick;
  }

  /*!
    \brief  Retrieve time elapsed between the last call to Start(), StartZero()
            or Reset() and; if running, now; if stopped, the last call to Stop().

    \return Elapsed time, in seconds, as a float.
  */
  float GetElapsedSeconds() const
  {
    std::chrono::duration<float> elapsed;

    if (m_isRunning)
      elapsed = std::chrono::steady_clock::now() - m_startTick;
    else
      elapsed = m_stopTick - m_startTick;

    return elapsed.count();
  }

  /*!
    \brief  Retrieve time elapsed between the last call to Start(), StartZero()
            or Reset() and; if running, now; if stopped, the last call to Stop().

    \return Elapsed time, in milliseconds, as a float.
  */
  float GetElapsedMilliseconds() const
  {
    std::chrono::duration<float, std::milli> elapsed;

    if (m_isRunning)
      elapsed = std::chrono::steady_clock::now() - m_startTick;
    else
      elapsed = m_stopTick - m_startTick;

    return elapsed.count();
  }

private:
  std::chrono::time_point<std::chrono::steady_clock> m_startTick;
  std::chrono::time_point<std::chrono::steady_clock> m_stopTick;
  bool m_isRunning = false;
};