高度なI/Oバウンドのプロセスを高速化するために複数のスレッドを使用したいと考えています。私は、ループ内のCSVファイルから取得したIDを使って休憩サービスを呼び出すことができるようにしたいと考えています。私が知ることができなかったことは、使いたいスレッドの量に応じてファイルをエレガントにチャンクに分割する方法です。私は困惑午前、と私は解決策は、コードブロックCSV.foreach(id_file.csv") do |id|...
である必要がある場所 ...Ruby:ファイルの一部を分割して読み込みスレッド数に応じて
require 'benchmark'
require 'csv'
FILE_RECORD_COUNT = File.open("path-to-csv","r").readlines.size
def setup(thread_count)
threads = []
thread_count.times do
threads << Thread.new do
fetches_per_thread = FILE_RECORD_COUNT/thread_count
fetches_per_thread.times do
CSV.foreach("id_file.csv") do |id|
response = RestClient.get("https://api.examplerest/names?id={#id}",{accept: :json})
# do some quick validation...
end
end
end
end
threads.each(&:join)
end
def run_benchmark
Benchmark.bm(20) do |bm|
[1, 2, 3, 5, 6, 10, 15, 30, 100].each do |thread_count|
bm.report("with #{thread_count} threads") do
setup(thread_count)
end
end
end
end
:
CSVファイルには、そのようなIDの単一の列が含まれています。私は、データを動的に分割して各スレッドに送り、残りの呼び出しをしたいと思います。私は手動でファイルを分割することができますが、私はそれを避けたいと思います。
私はこれをオンラインで見つかった例のベンチマークにしようとしました。スイートスポットがスレッド数のどこにあるのかを確認しました。
EDIT: BernardKの答えを使用して、私は私のコードスレッドを実行することができたし、次の結果を返しました:
| user | system | total | real |
with 1 threads 5.125000 2.594000 7.719000 (40.416162)
with 2 threads 1.625000 2.015000 3.640000 (28.571521)
with 3 threads 1.578000 1.625000 3.203000 (17.210526)
with 4 threads 1.578000 1.235000 2.813000 ( 8.496068)
with 5 threads 1.406000 1.250000 2.656000 ( 6.779216)
with 10 threads 1.875000 1.328000 3.203000 ( 5.069487)
with 15 threads 2.016000 1.640000 3.656000 ( 4.285426)
with 30 threads 2.125000 1.625000 3.750000 ( 3.817084)
with 100 threads 2.281000 1.375000 3.656000 ( 3.943304)
これはテストランでしたが、本当にこのようなスレッドを高速化する方法を示していますRubyコード!
エラーがあります( '@lines.each_slice'は' thread_count.times'を置き換える必要があります)。 – BernardK
@BernardK、よろしくお願いします。再投稿すると、変更内容が反映され、変更内容をお知らせします。 –
完了。 (以前のバージョンでは 'thread_count'回のファイルを読んでいました) – BernardK