File: timer_quantum.rb

package info (click to toggle)
ruby-timers 4.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 216 kB
  • sloc: ruby: 973; makefile: 8
file content (46 lines) | stat: -rw-r--r-- 943 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
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022-2025, 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.01)
		# 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