これが私のテストです:
require 'csv'
require 'benchmark'
small_csv_file = "test_data_small_50k.csv"
large_csv_file = "test_data_large_20m.csv"
Benchmark.bmbm do |x|
x.report("Small: CSV #parse") do
CSV.parse(File.open(small_csv_file), headers: true) do |row|
row
end
end
x.report("Small: CSV #foreach") do
CSV.foreach(small_csv_file, headers: true) do |row|
row
end
end
x.report("Large: CSV #parse") do
CSV.parse(File.open(large_csv_file), headers: true) do |row|
row
end
end
x.report("Large: CSV #foreach") do
CSV.foreach(large_csv_file, headers: true) do |row|
row
end
end
end
Rehearsal -------------------------------------------------------
Small: CSV #parse 0.950000 0.000000 0.950000 ( 0.952493)
Small: CSV #foreach 0.950000 0.000000 0.950000 ( 0.953514)
Large: CSV #parse 659.000000 2.120000 661.120000 (661.280070)
Large: CSV #foreach 648.240000 1.800000 650.040000 (650.062963)
------------------------------------------- total: 1313.060000sec
user system total real
Small: CSV #parse 1.000000 0.000000 1.000000 ( 1.143246)
Small: CSV #foreach 0.990000 0.000000 0.990000 ( 0.984285)
Large: CSV #parse 646.380000 1.890000 648.270000 (648.286247)
Large: CSV #foreach 651.010000 1.840000 652.850000 (652.874320)
ベンチマークは、8 GB のメモリを搭載した Macbook Pro で実行されました。結果は、パフォーマンスが CSV#parse または CSV#foreach を使用して統計的に同等であることを示しています。
ヘッダー オプションが削除されました (小さなファイルのみがテストされました):
require 'csv'
require 'benchmark'
small_csv_file = "test_data_small_50k.csv"
Benchmark.bmbm do |x|
x.report("Small: CSV #parse") do
CSV.parse(File.open(small_csv_file)) do |row|
row
end
end
x.report("Small: CSV #foreach") do
CSV.foreach(small_csv_file) do |row|
row
end
end
end
Rehearsal -------------------------------------------------------
Small: CSV #parse 0.590000 0.010000 0.600000 ( 0.597775)
Small: CSV #foreach 0.620000 0.000000 0.620000 ( 0.621950)
---------------------------------------------- total: 1.220000sec
user system total real
Small: CSV #parse 0.590000 0.000000 0.590000 ( 0.597594)
Small: CSV #foreach 0.610000 0.000000 0.610000 ( 0.604537)
ノート:
large_csv_file は small_csv_file とは構造が異なるため、2 つのファイル間で結果 (行/秒) を比較すると不正確になります。
small_csv_file には 50,000 レコードがありました
large_csv_file には 1,000,000 レコードがありました
Headers オプションを true に設定すると、行の各フィールドのハッシュが作成されるため、パフォーマンスが大幅に低下します (HeadersConverters セクションを参照してください: http://www.ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV .html )