Created
August 15, 2015 05:14
-
-
Save dukex/d5280f00aff305e0f5e8 to your computer and use it in GitHub Desktop.
fetcher_image.rb
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 'celluloid/current' | |
require 'rest-client' | |
require 'benchmark' | |
class ModelX | |
attr_accessor :url | |
def initialize(url) | |
@url = url | |
end | |
end | |
models = [] | |
50.times.each { |i| models.push ModelX.new("http://httpbin.org/redirect-to?url=https://randomuser.me/api/portraits/med/women/#{i}.jpg") } | |
# create fetcher | |
class ImageFetcher | |
include Celluloid | |
def do(url) | |
r = RestClient.get(url) # do same complex request here, and | |
return {got: r.net_http_res.uri.to_s, requested: url} | |
end | |
end | |
# create fetcher pool with size 20 | |
pool = ImageFetcher.pool(size: 20) | |
def fetch(pool, urls) | |
urls.map { |url| pool.future.do(url) }.map(&:value) | |
end | |
Benchmark.bmbm(2) do |bm| | |
bm.report('normal approach') do | |
models.each do |model| | |
ImageFetcher.new.do(model.url) | |
end | |
end | |
bm.report('using futures') do | |
fetch(pool, models.map(&:url)) # will returns a array with hash, the hash has the keys got and requested | |
end | |
end |
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
ruby image_fetcher.rb [ ruby-2.2.2p95 ] | |
Rehearsal --------------------------------------------------- | |
normal approach 0.400000 0.080000 0.480000 ( 45.859779) | |
using futures 0.360000 0.050000 0.410000 ( 2.979211) | |
------------------------------------------ total: 0.890000sec | |
user system total real | |
normal approach 0.360000 0.070000 0.430000 ( 48.330249) | |
using futures 0.360000 0.040000 0.400000 ( 3.153157) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment