在Ruby 2.2.0中编组比2.1.5慢

时间:2015-01-21 00:58:18

标签: ruby performance floating-point marshalling

我有一个复杂的对象my_object,我用

编组

Marshal.dump(my_object)

我已经在2.1.5p273和2.2.0中对该行调用100次的性能进行了基准测试,结果如下:

2.1.5  
                  user     system      total        real
Marshal Dump  7.310000   0.120000   7.430000 (  8.988470)
Marshal Dump  7.520000   0.050000   7.570000 (  8.210356)
Marshal Dump  7.610000   0.050000   7.660000 (  8.432685)

2.2.0
                  user     system      total        real
Marshal Dump 26.480000   0.150000  26.630000 ( 29.591742)
Marshal Dump 24.100000   0.300000  24.400000 ( 28.520397)
Marshal Dump 26.210000   0.210000  26.420000 ( 29.993412)

(我为每个版本运行了3次基准测试,要彻底。)

正如你所看到的,它在2.2.0 vs 2.1.5中的速度超过3倍。我把它归结为Marshal.dump因为,使用ruby-prof宝石,它向我展示了那条表现不佳的线条;但是我无法找到一种方法来获取Marshal.dump本身在探查器中调用的方法。

编辑:在经过多次实验后找到最小的复制品,我的答案

2 个答案:

答案 0 :(得分:4)

源位置为nil

Marshal.method(:dump).source_location
#=> nil

这意味着它是一个C实现的方法,并且没有更多的Ruby代码可以跟踪。换句话说,它是一种原子/基本方法。

如果您认为自己的结果有效,我建议您将其作为Ruby trunk中的错误发布。最新版本的Ruby确实发现了几个性能问题,因此您的情况似乎并不罕见。

答案 1 :(得分:1)

它是编组漂浮物导致减速。

require 'benchmark'

class ToBeMarshaled

  def initialize n
    @a = []
    n.times do |i|
      @a << i.to_f
    end
  end

end

tbm = ToBeMarshaled.new(10000)

n = 100

Benchmark.bm do |x|
  x.report("Marshal Dump") {for i in 1..n; Marshal.dump(tbm); end}
end

结果(每个Ruby版本运行基准测试3次):

2.1.5
                  user     system      total        real
Marshal Dump  0.640000   0.010000   0.650000 (  0.744080)
Marshal Dump  0.670000   0.000000   0.670000 (  0.758597)
Marshal Dump  0.650000   0.020000   0.670000 (  0.747583)

2.2.0
                  user     system      total        real
Marshal Dump 25.070000   0.220000  25.290000 ( 27.980023)
Marshal Dump 24.100000   0.160000  24.260000 ( 26.633049)
Marshal Dump 24.440000   0.230000  24.670000 ( 27.540826)
慢了~35倍。

如果您从该代码中取出“.to_f”,则会得到:

2.1.5
                  user     system      total        real
Marshal Dump  0.160000   0.000000   0.160000 (  0.180247)
Marshal Dump  0.180000   0.000000   0.180000 (  0.189485)
Marshal Dump  0.160000   0.010000   0.170000 (  0.191304)

2.2.0
                  user     system      total        real
Marshal Dump  0.120000   0.010000   0.130000 (  0.146710)
Marshal Dump  0.130000   0.010000   0.140000 (  0.159851)
Marshal Dump  0.130000   0.000000   0.130000 (  0.143917)

2.2.0略微超出2.1.5。