class PackerFiles::Utils::FastestURL
Given a list of URL, returns the fastest URL (to access) among them. This is done by launching several threads in parallel and estimating the time taken to access the contents of these URLs.
Public Class Methods
Creates a new object of type FastestURL
. slow_limit is used for signalling the response time (in seconds) of a web URL to be categorized as slow. Trials specifies the # of attempts the web URLs must be opened and closed.
# File lib/PackerFiles/Utils/FastestURL.rb, line 22 def initialize(slow_limit = 0.5 , trials = 1) @limit = slow_limit @trials = trials end
Public Instance Methods
Returns URLs sorted in terms of best access times from a list of input URLs.
# File lib/PackerFiles/Utils/FastestURL.rb, line 29 def best_urls(url_list) threads = url_list.map { |h| Thread.new {speed_trials(h) }} speeds = threads.map { |t| t.join; t.value } hash = Hash.new url_list.each_with_index do |url, index| hash[url] = speeds.at(index) if speeds.at(index) != @@error end hash.sort_by {|url, speed| speed} end
Private Instance Methods
This function is called in thread context only. It computes the time it takes for the various mirrors to return the index as a proxy for measuring it's speed.
# File lib/PackerFiles/Utils/FastestURL.rb, line 59 def estimate_speed(url) Benchmark.realtime do begin open(url) {|f| f.read} rescue Exception => e return @@error end end end
Compute the latency of a web url, multiple times via independent trials. This is called in thread context only.
# File lib/PackerFiles/Utils/FastestURL.rb, line 42 def speed_trials(url) total = 0.0 @trials.times do speed = estimate_speed(url) if speed >= @limit return @@error else total += speed end end return (total / @trials) end