File: stopwatch.rb

package info (click to toggle)
ruby-ddmetrics 1.0.1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 220 kB
  • sloc: ruby: 760; makefile: 3
file content (52 lines) | stat: -rw-r--r-- 981 bytes parent folder | download | duplicates (2)
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
# frozen_string_literal: true

module DDMetrics
  class Stopwatch
    class AlreadyRunningError < StandardError
      def message
        'Cannot start, because stopwatch is already running'
      end
    end

    class NotRunningError < StandardError
      def message
        'Cannot stop, because stopwatch is not running'
      end
    end

    class StillRunningError < StandardError
      def message
        'Cannot get duration, because stopwatch is still running'
      end
    end

    def initialize
      @duration = 0.0
      @last_start = nil
    end

    def start
      raise AlreadyRunningError if running?
      @last_start = Time.now
    end

    def stop
      raise NotRunningError unless running?
      @duration += (Time.now - @last_start)
      @last_start = nil
    end

    def duration
      raise StillRunningError if running?
      @duration
    end

    def running?
      !@last_start.nil?
    end

    def stopped?
      !running?
    end
  end
end