def rran()
s = 0
(0..10000000).each do |i|
s += i
end
end
def tfor()
n=0
s=0
while (n+=1) < 10000000
s+=n
end
end
[148] pry(main)> Benchmark.measure { tfor()}
=> #<Benchmark::Tms:0x000000029cf458
@cstime=0.0,
@cutime=0.0,
@label="",
@real=0.22141856199596077,
@stime=0.0,
@total=0.21999999999999997,
@utime=0.21999999999999997>
[149] pry(main)> Benchmark.measure { rran()}
=> #<Benchmark::Tms:0x00000002969388
@cstime=0.0,
@cutime=0.0,
@label="",
@real=0.3831686199409887,
@stime=0.0,
@total=0.3700000000000001,
@utime=0.3700000000000001>
如图 for 版本的循环比 range 版本的快很多。按道理应该是一样快才对啊。请大牛解释一下