Class: CompSci::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/compsci/timer.rb

Constant Summary collapse

SECS_PER_MIN =
60
MINS_PER_HOUR =
60
SECS_PER_HOUR =
SECS_PER_MIN * MINS_PER_HOUR

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.elapsed(&work) ⇒ Object



22
23
24
25
# File 'lib/compsci/timer.rb', line 22

def self.elapsed &work
  f = self.now
  return yield, self.since(f)
end

.elapsed_display(elapsed_ms, show_micro: false) ⇒ Object

HH::MM::SS.mmm.uuuuuuuu



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/compsci/timer.rb', line 41

def self.elapsed_display(elapsed_ms, show_micro: false)
  elapsed_s, ms = elapsed_ms.divmod 1000
  ms_only, ms_fraction = ms.round(8).divmod 1

  h = elapsed_s / SECS_PER_HOUR
  elapsed_s -= h * SECS_PER_HOUR
  m, s = elapsed_s.divmod SECS_PER_MIN

  hmsms = [[h, m, s].map { |i| i.to_s.rjust(2, '0') }.join(':'),
           ms_only.to_s.rjust(3, '0')]
  hmsms << (ms_fraction * 10 ** 8).round.to_s.ljust(8, '0') if show_micro
  hmsms.join('.')
end

.loop_avg(count: 999, seconds: 1, &work) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/compsci/timer.rb', line 27

def self.loop_avg(count: 999, seconds: 1, &work)
  i = 0
  start = self.now
  val = nil
  loop {
    val = yield
    i += 1
    break if i >= count
    break if self.since(start) > seconds
  }
  return val, self.since(start) / i
end

.nowObject



9
10
11
# File 'lib/compsci/timer.rb', line 9

def self.now
  Process.clock_gettime Process::CLOCK_MONOTONIC
end

.since(f) ⇒ Object



18
19
20
# File 'lib/compsci/timer.rb', line 18

def self.since f
  self.now - f
end

.timestamp(t = Time.now) ⇒ Object

YYYY-MM-DD HH::MM::SS.mmm



56
57
58
# File 'lib/compsci/timer.rb', line 56

def self.timestamp(t = Time.now)
  t.strftime "%Y-%m-%d %H:%M:%S.%L"
end

Instance Method Details

#elapsed(f = Timer.now) ⇒ Object



66
67
68
# File 'lib/compsci/timer.rb', line 66

def elapsed(f = Timer.now)
  f - @start
end

#elapsed_display(f = Timer.now) ⇒ Object Also known as: to_s, inspect



74
75
76
# File 'lib/compsci/timer.rb', line 74

def elapsed_display(f = Timer.now)
  Timer.elapsed_display(elapsed_ms(f))
end

#elapsed_ms(f = Timer.now) ⇒ Object



70
71
72
# File 'lib/compsci/timer.rb', line 70

def elapsed_ms(f = Timer.now)
  elapsed(f) * 1000
end

#restart(f = Timer.now) ⇒ Object Also known as: initialize



60
61
62
63
# File 'lib/compsci/timer.rb', line 60

def restart(f = Timer.now)
  @start = f
  self
end