gpt4 book ai didi

ruby-on-rails - Ruby/Rails 性能 : OpenURI vs NET:HTTP vs Curb vs Rest-Client

转载 作者:行者123 更新时间:2023-12-04 08:10:38 27 4
gpt4 key购买 nike

我正在访问不同的服务器以获取数据,并且在不同的类中尝试了不同的方法,使用基本的 http::net、curb、rest-client 和 open-uri

(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

最佳答案

通过从谷歌检索数据,我在下一个基准测试中得到了这种结果。

Warming up --------------------------------------
OpenURI 3.000 i/100ms
Net::HTTP 3.000 i/100ms
curb 3.000 i/100ms
rest_client 3.000 i/100ms
Calculating -------------------------------------
OpenURI 34.848 (±11.5%) i/s - 687.000 in 20.013469s
Net::HTTP 35.433 (±14.1%) i/s - 594.000 in 20.006947s
curb 31.612 (±19.0%) i/s - 465.000 in 20.021108s
rest_client 34.331 (±11.7%) i/s - 675.000 in 20.044486s

Comparison:
Net::HTTP: 35.4 i/s
OpenURI: 34.8 i/s - same-ish: difference falls within error
rest_client: 34.3 i/s - same-ish: difference falls within error
curb: 31.6 i/s - same-ish: difference falls within error

这是基准测试的源代码
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

环境:
  • AWS EC2 服务器
  • Ruby 版本 - 2.5.1p57
  • gem :curb-0.9.6、rest-client-2.0.2、 benchmark-ips-2.7.2

  • 备注:

    在运行这个基准测试之前不要忘记安装 gems
    gem install curb rest-client benchmark-ips

    在稳定的网络环境(如生产服务器)中运行以获得更准确的结果

    关于ruby-on-rails - Ruby/Rails 性能 : OpenURI vs NET:HTTP vs Curb vs Rest-Client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17619028/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com