在不同的变量范围内的表现?

时间:2013-08-17 10:03:18

标签: ruby performance compiler-construction

我写了一个简单的测试用例:

$g = 10
def fun_g a
  a += $g
end

def fun_l a
  l = 10
  a += l
end

def fun_gl a
  $gl = 10
  a += $gl
end

def test fun
  t = Time.now

  (10 ** 6).times { |n|
    method(fun).call(n)
  }

  puts(Time.now - t)
end

test :fun_g
test :fun_l
test :fun_gl

结果如下所示。似乎第一个函数fun_g是最快的,而fun_gl是最慢的。

1.249626
1.268355
1.30267

但我也得到结果,表明fun_l是最快的。

1.27436
1.25794
1.303973

理论上,哪一个应该是最快的? 如果我将示例更改为编译语言,结果是否仍然相同?编译器会将局部变量优化为全局变量吗?

1 个答案:

答案 0 :(得分:3)

我已将此转换为使用STDLIB benchmark并获得此结果

require 'benchmark'

iterations = 10 ** 7
$global = 0
local = 0
@instance = 0
Benchmark.bmbm(8) do |x|
  x.report('global') {iterations.times { $global } }
  x.report('local') {iterations.times { local } }
  x.report('instance') {iterations.times { @instance  } }
end

结果:

Rehearsal --------------------------------------------
global     1.580000   0.010000   1.590000 (  1.600952)
local      1.540000   0.000000   1.540000 (  1.555683)
instance   1.600000   0.000000   1.600000 (  1.642781)
----------------------------------- total: 4.730000sec

               user     system      total        real
global     1.560000   0.000000   1.560000 (  1.575711)
local      1.540000   0.000000   1.540000 (  1.547040)
instance   1.600000   0.010000   1.610000 (  1.618772)

使用benchmark-ips gem:

require 'benchmark/ips'

$global = 0
local = 0
@instance = 0

Benchmark.ips do |x|
  x.report('global') { $global }
  x.report('local') { local }
  x.report('instance') { @instance }
  x.compare!
end

此时在我的机器上提供以下报告,并且可能提供更容易阅读的比较:

Calculating -------------------------------------
              global    34.310k i/100ms
               local    34.461k i/100ms
            instance    34.383k i/100ms
-------------------------------------------------
              global      3.154M (± 2.9%) i/s -     15.748M
               local      3.205M (± 4.5%) i/s -     15.990M
            instance      3.153M (± 3.1%) i/s -     15.747M

Comparison:
               local:  3205049.9 i/s
              global:  3153595.5 i/s - 1.02x slower
            instance:  3152813.3 i/s - 1.02x slower

您只比较了局部变量和全局变量,但忽略了实例变量。

任何一个都有微不足道的差异,这实际上是一件好事。

我不确定这会回答你的问题,但希望有所帮助。

相关问题