Module: TIMEx::Clock

Extended by:
Clock
Included in:
Clock
Defined in:
lib/timex/clock.rb

Overview

Note:

Uses Thread.current.thread_variable_get/set(:timex_clock) so every fiber in a thread shares one clock context (deadline shielding, AutoCheck, tests).

Thread-scoped clock abstraction for monotonic and wall time in nanoseconds.

Production code reads RealClock unless TIMEx::Configuration#clock= or Test.with_virtual_clock overrides the current binding via thread_variable_* (not fiber-local storage).

See Also:

Defined Under Namespace

Modules: RealClock Classes: VirtualClock

Constant Summary collapse

NS_PER_SECOND =
1_000_000_000

Instance Method Summary collapse

Instance Method Details

#current#monotonic_ns, #wall_ns

Returns the clock object consulted by #monotonic_ns and #wall_ns.

Returns:



39
40
41
# File 'lib/timex/clock.rb', line 39

def current
  Thread.current.thread_variable_get(:timex_clock) || TIMEx.config.clock || RealClock
end

#monotonic_nsInteger

Returns monotonic time in nanoseconds from the active clock.

Returns:

  • (Integer)

    monotonic time in nanoseconds from the active clock



22
23
24
# File 'lib/timex/clock.rb', line 22

def monotonic_ns
  current.monotonic_ns
end

#now_secondsFloat

Returns monotonic time expressed in fractional seconds.

Returns:

  • (Float)

    monotonic time expressed in fractional seconds



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

def now_seconds
  monotonic_ns / NS_PER_SECOND.to_f
end

#wall_nsInteger

Returns wall-clock time in nanoseconds from the active clock.

Returns:

  • (Integer)

    wall-clock time in nanoseconds from the active clock



27
28
29
# File 'lib/timex/clock.rb', line 27

def wall_ns
  current.wall_ns
end

#with(clock) { ... } ⇒ Object

Binds clock for the duration of the block on the current thread.

Parameters:

Yields:

  • runs with the thread-local clock swapped

Returns:

  • (Object)

    the block’s return value



48
49
50
51
52
53
54
# File 'lib/timex/clock.rb', line 48

def with(clock)
  previous = Thread.current.thread_variable_get(:timex_clock)
  Thread.current.thread_variable_set(:timex_clock, clock)
  yield
ensure
  Thread.current.thread_variable_set(:timex_clock, previous)
end