Last active
August 27, 2019 09:45
-
-
Save thomet/474bd082e15705fdba2906a9f4ca360a to your computer and use it in GitHub Desktop.
A simple progress bar script to load directly in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @example Usage | |
# require 'open-uri' | |
# eval(open('https://gist.githubusercontent.com/thomet/474bd082e15705fdba2906a9f4ca360a/raw/5ed83ff172a408601232d5306cf214ba3bd75775/progress_bar.rb') {|f| f.read }) | |
# | |
# progress_bar(1_000) do | |
# # do something | |
# end | |
# | |
# > Progress [======================================================== 56.90 % \ (~43 seconds) | |
def progress_bar(iteration_count, &block) | |
spinner = ['\\', '|', '/', '-'] | |
current_spinner = 0 | |
progress = 'Progress [' | |
time_history = [] | |
last_percentage = 0 | |
print progress | |
iteration_count.times do |i| | |
time = Time.now | |
block.call | |
needed = Time.now - time | |
time_history << needed | |
time_history = time_history.last(20) | |
time_average = time_history.inject{ |sum, el| sum + el }.to_f / time_history.size | |
j = i + 1 | |
total_time = time_average * iteration_count | |
left_time = total_time - (j * time_average) | |
denominator = iteration_count/100.0 | |
current_percentage = (j / denominator).to_i | |
progress << "=" if last_percentage < current_percentage | |
last_percentage = current_percentage | |
print "\r" | |
printable = "#{progress} #{'%.2f' % (j / denominator)} %" | |
if iteration_count > j | |
formatted_left = if left_time < 60 | |
"#{left_time.round} seconds" | |
else | |
"#{(left_time/60).round} Minutes" | |
end | |
print "#{printable} #{spinner[current_spinner]} (~#{formatted_left})" | |
else | |
print "#{printable}]" | |
end | |
# force the output to appear immediately when using print | |
# by default when \n is printed to the standard output, the buffer is flushed. | |
$stdout.flush | |
current_spinner += 1 | |
current_spinner = 0 if current_spinner >= spinner.length | |
end | |
puts "\nDone!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment