Ruby ruby 循环性能计算.

lb563 · July 10, 2012 · Last by heliang7 replied at July 13, 2012 · 3778 hits

贴出测试代码:

#for
def tfor
    o = Time.now
    (0..100000000).each do |i|
        i
    end
    n = Time.now
    puts "total cast time:#{n-o}"
end 

#while
def twhile
    o = Time.now
    i=100000000
    while (i>0) 
        i-=1
    end
    n = Time.now
    puts "total cast time:#{n-o}"
end
tfor     # total cast time:9.864268
twhile # total cast time:3.355015

如上面的输出结果,可见用 while 的比较的快。

你无视了 block 的开销啊...

不知道这样写是不是使用了 block

def tfor
    o = Time.now
    for i in 0..100000000
        i
    end
    n = Time.now
    puts "total cast time:#{n-o}"
end 

#while
def twhile
    o = Time.now
    i=100000000
    while (i>0) 
        i-=1
    end
    n = Time.now
    puts "total cast time:#{n-o}"
end

total cast time:9.846828393 total cast time:3.756857119

还是 while 比较快!

提醒一下, 我觉得, 不应该忽略, 通过i, 定位到容器中当前元素的性能开销。 如果 array,没什么问题, 如果是 hash 或者其他数据结构,就有问题了。

这又有什么意义呢?难道做性能优化的时候要把 each 换成 for,把 for 换成 while?

#5 楼 @hooopo for 是 each 的包装,应该不会快吧。

这里我猜是不是因为 while 的 yield 不用传值过去,而 each 有传呢。 我猜错了,看了一下,是因为 while 不是执行 block, each 需要执行。

#6 楼 @hhuai 其实这个很难从理论上分析哪个快的,不同的 Ruby 实现或许还不一样。。所以根本不用考虑,,,当需要考虑 Ruby 里用 for 还是 while 能提高性能的时候,那么还是别用 Ruby 算了。

#7 楼 @hooopo 为啥我觉得他们的机器都快得离谱啊。我这少个零,也分别要

total cast time:5.62507
total cast time:3.195106

还是我机器太烂了...

#8 楼 @bhuztez

ruby 2.0.0dev (2012-06-30 trunk 36257) [x86_64-linux]
total cast time:5.928291172
total cast time:2.927292006
ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux], MBARI 0x6770, Ruby Enterprise Edition 2011.03
total cast time:12.951016
total cast time:19.63892

真的太烂了吧。。。我的机器开个 Netbeans 都卡还能跑成这样呢,没少零。

呃,,这结果对比也说明了不同 Ruby 实现哪个快是不一定的:-)

#9 楼 @hooopo

看来 Ruby 2 快了不少啊,的确是 1.8.7 比较慢的缘故

$ ruby -v
ruby 1.8.7 (2012-02-08 patchlevel 358) [x86_64-linux]

#10 楼 @bhuztez 其实和 1.9 差不多。。

#11 楼 @hooopo 我一直认为 Ruby 1.9 就是 2 啊...

#12 楼 @bhuztez 这。。明显 1.9!= 2 嘛!

#12 楼 @bhuztez 四舍五入吗? #13 楼 @hooopo 估计是

1.9.round # is 2

Martz 承诺 2.0,ruby 的性能不在被人诟病,目前看来不错啊

You need to Sign in before reply, if you don't have an account, please Sign up first.