hur.st's bl.aagh

BSD, Ruby, Rust, Rambling

monotime

Rust-style monotonic clocks in Ruby

[ruby] [rust]

Monotime offers an alternative to the typical method of monotonic timekeeping in Ruby:

# Bog standard Ruby
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
do_something
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start

# With monotime
require 'monotime'
include Monotime

start = Instant.now
do_something
elapsed = start.elapsed

# or
elapsed = Duration.measure { do_something }

It’s less fiddly, and uses proper types wrapping elapsed times in nanoseconds, which is about as close to the native representations as Ruby gets.

You can do maths on them, sleep using them, convert between them, and format them:

(Duration.millis(42) + Duration.secs(1)).to_s  # => "1.042s"
(Duration.millis(42) - Duration.secs(1)).to_s  # => "-958ms"
(Duration.secs(42) * 2).to_s                   # => "84s"
(Duration.secs(42) / 2).to_s                   # => "21s"

# Instant - Duration => Instant
(Instant.now - Duration.secs(1)).elapsed.to_s  # => "1.000014627s"

# Instant - Instant => Duration
(Instant.now - Instant.now).to_s               # => "-5.585μs"

Duration.secs(60).sleep

next_minute = Instant.now + Duration.secs(60)
sleep 5 # do some work
next_minute.sleep # sleeps for ~55 seconds