這是Sieve of Eratosthenes的實現。現在如何優化這一點的ruby代碼來加快速度?
class PrimeGenerator
def self.get_primes_between(x, y)
sieve_array = Array.new(y) {|index|
(index == 0 ? 0 : index+1)
}
position_when_we_can_stop_checking = Math.sqrt(y).to_i
(2..position_when_we_can_stop_checking).each{|factor|
sieve_array[(factor).. (y-1)].each{|number|
sieve_array[number-1] = 0 if isMultipleOf(number, factor)
}
}
sieve_array.select{|element|
((element != 0) && ((x..y).include? element))
}
end
def self.isMultipleOf(x, y)
return (x % y) == 0
end
end
我這樣做是爲了一個「提交問題的解決方案,因爲你有時間殺」的網站。我選擇了紅寶石作爲我的impl語言,但是我宣佈超時。 我做了一些基準
require 'benchmark'
Benchmark.bmbm do |x|
x.report ("get primes") { PrimeGenerator.get_primes_between(10000, 100000)}
end
紅寶石1.9.1p0(2009-01-30的修訂21907)[I386-mswin32]
L:\Gishu\Ruby>ruby prime_generator.rb
Rehearsal ----------------------------------------------
get primes 33.953000 0.047000 34.000000 (34.343750)
------------------------------------ total: 34.000000sec
user system total real
get primes 33.735000 0.000000 33.735000 (33.843750)
紅寶石1.8.6(2007-03-13 PATCHLEVEL 0) [I386-mswin32]
Rehearsal ----------------------------------------------
get primes 65.922000 0.000000 65.922000 (66.110000)
------------------------------------ total: 65.922000sec
user system total real
get primes 67.359000 0.016000 67.375000 (67.656000)
所以我重做C#中的東西2.0/VS 2008 - > 722毫秒
所以,現在這刺激我思考這是我的實現問題,或者是這種寬泛的語言之間的差異? (我很驚訝與1.9的Ruby VM ...直到我不得不去與C#:)比較一下
UPDATE: 竟然是我的「放 - 埃拉托色尼到恥辱適應」畢竟:) 消除不必要的循環迭代是主要的優化。如果有人對細節感興趣..你可以閱讀here;反正這個問題太長了。
謝謝。瞭解你的代碼段很有趣......感覺再次成爲程序員的樂趣。此外,它的簡潔與Ruby的方式 – Gishu 2009-04-22 20:13:33