Class: Sus::Clock
Overview
Represents a clock for measuring elapsed time during test execution.
Class Method Summary collapse
-
.start! ⇒ Object
Create a new clock and start it immediately.
Instance Method Summary collapse
-
#<=>(other) ⇒ Object
Compare this clock’s duration with another value.
-
#duration ⇒ Object
Get the current elapsed duration.
-
#initialize(duration = 0.0) ⇒ Clock
constructor
Initialize a new clock.
-
#ms ⇒ Object
Get the duration in milliseconds.
-
#reset!(duration = 0.0) ⇒ Object
Reset the clock to a specific duration.
-
#start! ⇒ Object
Start the clock.
-
#stop! ⇒ Object
Stop the clock and return the final duration.
-
#to_f ⇒ Object
Convert the duration to a float.
-
#to_s ⇒ Object
Get a human-readable string representation of the duration.
Constructor Details
#initialize(duration = 0.0) ⇒ Clock
Initialize a new clock.
19 20 21 |
# File 'lib/sus/clock.rb', line 19 def initialize(duration = 0.0) @duration = duration end |
Class Method Details
.start! ⇒ Object
Create a new clock and start it immediately.
13 14 15 |
# File 'lib/sus/clock.rb', line 13 def self.start! self.new.tap(&:start!) end |
Instance Method Details
#<=>(other) ⇒ Object
Compare this clock’s duration with another value.
38 39 40 |
# File 'lib/sus/clock.rb', line 38 def <=>(other) duration <=> other.to_f end |
#duration ⇒ Object
Get the current elapsed duration.
25 26 27 28 29 30 31 32 33 |
# File 'lib/sus/clock.rb', line 25 def duration if @start_time now = Process.clock_gettime(Process::CLOCK_MONOTONIC) @duration += now - @start_time @start_time = now end return @duration end |
#ms ⇒ Object
Get the duration in milliseconds.
50 51 52 |
# File 'lib/sus/clock.rb', line 50 def ms duration * 1000.0 end |
#reset!(duration = 0.0) ⇒ Object
Reset the clock to a specific duration.
70 71 72 |
# File 'lib/sus/clock.rb', line 70 def reset!(duration = 0.0) @duration = duration end |
#start! ⇒ Object
Start the clock.
75 76 77 |
# File 'lib/sus/clock.rb', line 75 def start! @start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) end |
#stop! ⇒ Object
Stop the clock and return the final duration.
81 82 83 84 85 86 87 88 89 |
# File 'lib/sus/clock.rb', line 81 def stop! if @start_time now = Process.clock_gettime(Process::CLOCK_MONOTONIC) @duration += now - @start_time @start_time = nil end return duration end |
#to_f ⇒ Object
Convert the duration to a float.
44 45 46 |
# File 'lib/sus/clock.rb', line 44 def to_f duration end |
#to_s ⇒ Object
Get a human-readable string representation of the duration.
56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/sus/clock.rb', line 56 def to_s duration = self.duration if duration < 0.001 "#{(duration * 1_000_000).round(1)}µs" elsif duration < 1.0 "#{(duration * 1_000).round(1)}ms" else "#{duration.round(1)}s" end end |