Class: ConsoleProgress::ETA

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

Constant Summary collapse

ATTR =
[:steps, :step, :step_time, :times,
:avg_time, :format, :start_time,
:seconds, :message_prefix,
:elapsed_time, :time_left]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(steps, format: nil) ⇒ ETA

Returns a new instance of ETA.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/console_progress.rb', line 12

def initialize(steps, format: nil)
  @steps = steps
  @format = format
  @message_prefix = 'ETA'
  @format ||= "{{message_prefix}}: {{step}}/{{steps}} "\
              "Remaining: {{time_left}} "\
              "Took: {{step_time}}s Avg: {{avg_time}}s "\
              "Elapsed: {{elapsed_time}}"
  @step = 0
  @times = []
  start
end

Class Method Details

.exampleObject



76
77
78
79
80
81
82
83
# File 'lib/console_progress.rb', line 76

def self.example
  eta = ConsoleProgress::ETA.new(100)
  eta.start
  100.times do
    puts eta.progress
    sleep 2
  end
end

.example2Object



85
86
87
88
89
90
91
92
# File 'lib/console_progress.rb', line 85

def self.example2
  eta = ConsoleProgress::ETA.new(100)
  eta.start
  100.times do
    eta.put_if(10)
    sleep 1
  end
end

Instance Method Details

#log(msg = @message_prefix) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/console_progress.rb', line 54

def log(msg = @message_prefix)
  out = @format.dup
  ATTR.each do |m|
    out.gsub!("{{#{m}}}", send(m).to_s)
  end
  out
end

#progress(msg = nil, current_step: @step) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/console_progress.rb', line 30

def progress(msg = nil, current_step: @step)
  @message_prefix = msg if msg
  t = Time.now
  @step_time = t - @step_time_start

  @elapsed_time = seconds_to_time(t - @start_time)

  @times << @step_time
  asum = @times.reduce(0, :+)
  @avg_time =  asum / @times.size
  @times = [asum] if @times.size % 100 == 0

  steps_left = @steps - @step
  @step = current_step + 1

  @seconds = steps_left * @avg_time
  @time_left = seconds_to_time(@seconds)

  @step_time = '%.2f' % @step_time
  @avg_time = '%.2f' % @avg_time
  @step_time_start = t
  log
end

#put_if(limit) ⇒ Object



62
63
64
65
# File 'lib/console_progress.rb', line 62

def put_if(limit)
  out = progress
  puts out if @step % limit == 0
end

#seconds_to_time(t) ⇒ Object



67
68
69
70
71
72
73
74
# File 'lib/console_progress.rb', line 67

def seconds_to_time(t)
  mm, ss = t.divmod(60)
  hh, mm = mm.divmod(60)
  dd, hh = hh.divmod(24)
  [dd, hh, mm, ss].delete_if {|r| r == 0}
    .map {|r| '%02d' % r.to_i}
    .join(':')
end

#startObject



25
26
27
28
# File 'lib/console_progress.rb', line 25

def start
  @start_time = Time.now
  @step_time_start = @start_time
end