-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathtimer_quantum.rb
45 lines (35 loc) · 940 Bytes
/
timer_quantum.rb
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
# Released under the MIT License.
# Copyright, 2022, by Samuel Williams.
class TimerQuantum
def self.resolve
self.new.to_f
end
def to_f
precision
end
private
def precision
@precision ||= self.measure_host_precision
end
def measure_host_precision(repeats: 100, duration: 0.0001)
# Measure the precision sleep using the monotonic clock:
start_time = self.now
repeats.times do
sleep(duration)
end
end_time = self.now
actual_duration = end_time - start_time
expected_duration = repeats * duration
if actual_duration < expected_duration
warn "Invalid precision measurement: #{actual_duration} < #{expected_duration}"
return 0.1
end
# This computes the overhead of sleep, called `repeats` times:
return actual_duration - expected_duration
end
def now
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
end
TIMER_QUANTUM = TimerQuantum.resolve
p timer_quantum: TIMER_QUANTUM