我正在嘗試使用賽璐珞異步處理一些.csv數據。我讀過使用期貨使您能夠在主線程終止之前等待一組角色完成。我看過some examples,證明了這一點。賽璐珞期貨不會比同步計算快嗎?
但是,當我在我的示例代碼中實現它時,事實證明使用futures並不比同步處理更快。任何人都可以看到我做錯了什麼?
require 'smarter_csv'
require 'celluloid/current'
require 'benchmark'
class ImportActor
include Celluloid
def process_row(row)
100000.times {|n| n}
end
end
def do_all_the_things_with_futures
pool = ImportActor.pool(size: 10)
SmarterCSV.process("all_the_things.csv").map do |row|
pool.future(:process_row,row)
end.map(&:value)
end
def do_all_the_things_insync
pool = ImportActor.pool(size: 10)
SmarterCSV.process("all_the_things.csv") do |row|
pool.process_row(row)
end
end
puts Benchmark.measure { do_all_the_things_with_futures}
puts Benchmark.measure { do_all_the_things_insync }
2.100000 0.030000 2.130000(2.123381)
2.060000 0.020000 2.080000(2.069357)
[完成了4.6S]
添加'睡眠1'而不是我最初的迭代有訣竅。異步方法的速度提高了10倍。令人驚訝的是,徹底的答案。乾杯。 –
很高興它有幫助;安裝jruby並不難(如果使用rvm,或者我建議使用ruby-build和chruby);如果您在JRuby下嘗試您的原始示例,您應該看到顯着加速!除非您的計算機上有10個CPU核心,否則不是10x,而是顯着的。嘗試和比較會很有趣。 – jrochkind