2013-07-12 41 views
7

我正在訪問不同的服務器以獲取數據,並且我嘗試了不同類中的不同方法,使用基本的http :: net,curb,rest-client和open-uriRuby/Rails性能:OpenURI vs NET:HTTP vs Curb vs Rest-Client

(1)如何在一般的Ruby/Rails中測量性能? (2)你認爲哪種方法更快?從所有4種不同的方法

樣品的編號:

url = "..." 
    begin 
    io_output = open(url, :http_basic_authentication => [@user_id, @user_password]) 
    rescue => e 
    error = e.message #for debugging return this 
    return '-' 
    else 
    output = io_output.read 

require 'net/https' 
uri = URI.parse("...") 
http = Net::HTTP.new(uri.host, uri.port) 
http.use_ssl = true 
http.verify_mode = OpenSSL::SSL::VERIFY_PEER 
data = http.get(uri.request_uri) #http request status 
res = Net::HTTP.get_response(uri) 
puts res.body if res.is_a?(Net::HTTPSuccess) 

require 'curb' 
url = "..." 
c = Curl::Easy.new(url) do |curl| 
curl.headers["Content-type"] = "application/json" 
curl.headers["Authorization"] = "Token ..." 
end 
c.perform 
puts c.body_str 

url = "..." 
resource = RestClient::Resource.new(url, 
     :headers => { :Authorization => "Token ...", 
     :content_type => "application/json"}) 
begin 
output = resource.get 
rescue => e 
error = e.message #for debugging return this 
return '-' 
else ... 
end 
+0

我發現http://www.ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html我會試試 – nevermind

+0

發表你的結果作爲答案。我很好奇看到他們。 –

+1

我要做更多的測試,但!爲每個客戶端運行5次:http :: net〜13秒open-uri〜8 seconds rest-client〜6.9和curb〜6.3秒 – nevermind

回答

5

我通過基準測試獲得了這種結果,從Google獲取數據。

Warming up -------------------------------------- 
      OpenURI  1.000 i/100ms 
      Net::HTTP  1.000 i/100ms 
       curb  1.000 i/100ms 
     rest_client  1.000 i/100ms 
Calculating ------------------------------------- 
      OpenURI  10.258 (± 9.7%) i/s - 199.000 in 20.003783s 
      Net::HTTP  18.272 (± 5.5%) i/s - 362.000 in 20.047560s 
       curb  17.873 (± 5.6%) i/s - 356.000 in 20.019155s 
     rest_client  13.688 (±21.9%) i/s - 258.000 in 20.9s 

Comparison: 
      Net::HTTP:  18.3 i/s 
       curb:  17.9 i/s - same-ish: difference falls within error 
     rest_client:  13.7 i/s - 1.33x slower 
      OpenURI:  10.3 i/s - 1.78x slower 

這裏是測試的源代碼

require 'benchmark/ips' 
require 'open-uri' 
require 'net/http' 
require 'curb' 
require 'rest-client' 

google_uri = URI('http://www.google.com/') 
google_uri_string = google_uri.to_s 

Benchmark.ips do |x| 
    x.config(time: 20, warmup: 10) 
    x.report('OpenURI') { open(google_uri_string) } 
    x.report('Net::HTTP') { Net::HTTP.get(google_uri) } 
    x.report('curb') { Curl.get(google_uri_string) } 
    x.report('rest_client') { RestClient.get(google_uri_string) } 
    x.compare! 
end 

注:

不要忘記安裝寶石之前運行這個測試

gem install curb rest-client benchmark-ips 

要獲得在穩定的網絡環境下運行更準確的結果,如生產rvers

+1

我記得路由器是我測試中速度最快的路由器 – nevermind

+2

如果你仍然擁有它,你可以在這裏添加你的代碼,以便其他人可以爲自己做這個嗎? – kbrock