Class: Sus::Clock

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(duration = 0.0) ⇒ Clock

Returns a new instance of Clock.



14
15
16
# File 'lib/sus/clock.rb', line 14

def initialize(duration = 0.0)
	@duration = duration
end

Class Method Details

.start!Object



10
11
12
# File 'lib/sus/clock.rb', line 10

def self.start!
	self.new.tap(&:start!)
end

Instance Method Details

#<=>(other) ⇒ Object



28
29
30
# File 'lib/sus/clock.rb', line 28

def <=>(other)
	duration <=> other.to_f
end

#durationObject



18
19
20
21
22
23
24
25
26
# File 'lib/sus/clock.rb', line 18

def duration
	if @start_time
		now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
		@duration += now - @start_time
		@start_time = now
	end
	
	return @duration
end

#msObject



36
37
38
# File 'lib/sus/clock.rb', line 36

def ms
	duration * 1000.0
end

#reset!(duration = 0.0) ⇒ Object



52
53
54
# File 'lib/sus/clock.rb', line 52

def reset!(duration = 0.0)
	@duration = duration
end

#start!Object



56
57
58
# File 'lib/sus/clock.rb', line 56

def start!
	@start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
end

#stop!Object



60
61
62
63
64
65
66
67
68
# File 'lib/sus/clock.rb', line 60

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



32
33
34
# File 'lib/sus/clock.rb', line 32

def to_f
	duration
end

#to_sObject



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/sus/clock.rb', line 40

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