Class: Sus::Clock

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/sus/clock.rb

Overview

Represents a clock for measuring elapsed time during test execution.

Class Method Summary collapse

Instance Method Summary collapse

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

#durationObject

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

#msObject

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_fObject

Convert the duration to a float.



44
45
46
# File 'lib/sus/clock.rb', line 44

def to_f
	duration
end

#to_sObject

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