Rubinius和JRuby怎么可能这么慢?

时间:2014-06-04 23:40:38

标签: ruby jruby benchmarking microbenchmark rubinius

我决定看看迭代哈希数组需要多长时间。以下是代码:

pairs = [{name: "firstname", value: "string"},{name: "lastname", value: "string"},{name: "country", value: "string"},{name: "city", value: "string"},{name: "state", value: "string"},{name: "company", value: "string"},{name: "year", value: "string"},{name: "political_affiliation", value: "string"},{name: "social_security_number", value: "string"}] * 1000
blank = {}

start = Time.now
pairs.each do |pair|
  blank[pair[:name]] = pair[:value]
end

p Time.now - start

通过从循环前的当前时间减去循环后的当前时间来计算时间。

根据代码中的数学计算,这是计算在YARV 2.1.1中所花费的时间:

0.001962017

这是在Rubinius 2.2.6中花了多长时间:

0.022598

和jRuby 1.7.12

0.022317

据说Rubinius和jRuby比YARV具有性能优势。为什么他们花费的时间几乎是执行相同基本操作的12倍?这是正常的还是我有不正确的配置?

1 个答案:

答案 0 :(得分:10)

您的基准测试时间太短,受到环境负载的影响。根据我的经验,为了获得可靠的基准测试,您必须获得至少10秒的时间,以减少预热时间。大约10秒钟我希望JRuby是最高性能的,其次是Ruby和Rubinius。

让我们看看:

# so_24049371.rb

require 'benchmark'

# NOTE THIS: YOU SHOULD TWEAK IT IN ORDER TO HAVE BENCHMARKS OF ~ 10 SECONDS
MULTIPLIER = 5_000_000
pairs = [{name: "firstname", value: "string"},{name: "lastname", value: "string"},{name: "country", value: "string"},{name: "city", value: "string"},{name: "state", value: "string"},{name: "company", value: "string"},{name: "year", value: "string"},{name: "political_affiliation", value: "string"},{name: "social_security_number", value: "string"}] \
  * MULTIPLIER
blank = {}

puts Benchmark.measure {
  pairs.each do |pair|
    blank[pair[:name]] = pair[:value]
  end
}

# so_24049371.fish

source (rbenv init -|psub)

for ruby_version in 2.1.2 rbx-2.2.7 jruby-1.7.12
  rbenv shell $ruby_version
  ruby -v
  ruby so_24049371.rb
end

这是我机器上的输出(我使用fish shell + rbenv,你应该编写自己的脚本):

> fish so_24049371.fish
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
  8.190000   0.000000   8.190000 (  8.188726)
rubinius 2.2.7 (2.1.0 build 2014-05-20 JI) [x86_64-linux-gnu]
 14.359762   0.003525  14.363287 ( 14.193565)
jruby 1.7.12 (2.0.0p195) 2014-04-15 643e292 on Java HotSpot(TM) 64-Bit Server VM 1.7.0_55-b13 [linux-amd64]
  4.570000   0.000000   4.570000 (  4.367000)

正如我想的那样,JRuby是最快的4.367000,而Ruby是8.188726,最后的Rubinius是14.193565。