开发者

A Simple Ruby Script Freezes My Machine

CONSTANT = 1000000000000000000
array = (1..CONSTANT).to_a

start = Time.now
array.each do |i|
  if 1000 < i < CONSTANT * 9 / 10

  elsif i > CONSTANT * 9 / 10

  else

  end 
end
finish = Time.now

puts "Running time: #{finish - start} seconds"

I wrote the above script in an attempt to figure out how much time saving could b开发者_如何学Goe achieved by re-ordering the control branches. The script froze my machine immediately after being run, which couldn't be terminated via CTL + C. Could someone please point out what happened there?


You're iterating over a huge number.

Lets say your CPU can iterate one array item per nanosecond (which is good!), that means it'll take 1e9 seconds to iterate over the array. That's 31 years!

Your constant is far, far too large.


You are creating a huge array which you don't even need. That is forcing your machine to start paging (it would take up 5% of the 64-bit address space and your machine certainly doesn't have that much RAM). Your code is not making it to the loop (the condition in the if statement isn't valid ruby).

CONSTANT = 1000 
# start with something small, then increase by 10 
# 10000000 works for me.

start = Time.now
CONSTANT.times do |i|
  if 1000 < i && CONSTANT * 9 / 10

  elsif i > CONSTANT * 9 / 10

  else

  end 
end
finish = Time.now

puts "Running time: #{finish - start} seconds"


What happened is that you tried to create a rather large array:

CONSTANT = 1000000000000000000
array = (1..CONSTANT).to_a

And your machine got upset with you. You might have better luck using the Range on its own without the to_a call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜