Created
July 22, 2014 08:47
-
-
Save mat/838c84ce6a1440f433d4 to your computer and use it in GitHub Desktop.
Guesstimator
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
require 'benchmark' | |
class Guesstimator | |
@@instances={} | |
attr_accessor :total_operations | |
attr_accessor :remaining_operations | |
attr_reader :exp_moving_average | |
SMOOTHING_FACTOR = 0.005 | |
def estimated_time_arrival | |
Time.now + estimated_time_remaining | |
end | |
def estimated_time_remaining | |
remaining_operations * @exp_moving_average | |
end | |
def ops_per_sec | |
1.0 / @exp_moving_average | |
end | |
def run_operation | |
runtime_ms = Benchmark.realtime do | |
yield() | |
end | |
@remaining_operations -= 1 | |
@exp_moving_average ||= runtime_ms | |
@exp_moving_average = SMOOTHING_FACTOR * runtime_ms + (1-SMOOTHING_FACTOR) * @exp_moving_average; | |
runtime_ms | |
end | |
def self.format_estimated_time(secs) | |
hours = (secs/3600).to_i | |
minutes = (secs/60.0 - hours * 60.0).to_i | |
seconds = (secs- (minutes * 60 + hours * 3600.0)) | |
sprintf("%02d:%02d:%02d", hours, minutes, seconds) | |
end | |
def self.estimate_by_total_operations(total_operation_count, operation_id, &block) | |
guesstimator = get_or_create_instance(operation_id, total_operation_count) | |
runtime_ms = guesstimator.run_operation(&block) | |
print_progress(guesstimator, operation_id, runtime_ms) | |
end | |
def self.print_progress(guesstimator, operation_id, runtime_ms) | |
puts "#{operation_id}: last=#{runtime_ms}s, avg=#{guesstimator.exp_moving_average}s, avg_ops/s=#{guesstimator.ops_per_sec} ops_remaining=#{guesstimator.remaining_operations}, time_remaining=#{self.format_estimated_time(guesstimator.estimated_time_remaining)}, eta=#{guesstimator.estimated_time_arrival}" | |
end | |
def self.get_or_create_instance(operation_id, total_operation_count) | |
if obj = @@instances[operation_id] | |
return obj | |
end | |
instance = self.new | |
instance.total_operations = total_operation_count | |
instance.remaining_operations = total_operation_count | |
@@instances[operation_id] = instance | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment