CSVのパース

Rubyの標準ライブラリのcsvは遅い、というのはよく聞く話です。
代替ではfastercsvが有名なように思いますが、他にもいろいろあったので調べてみました。
簡単な速度比較です。

環境

vmware player上のfedora core5(メモリ256M)
ruby 1.8.6 (2008-03-03 patchlevel 114)
gcc バージョン 4.1.1 20061011 (Red Hat 4.1.1-30)

テストデータ

例によって郵便番号CSV

csv

標準添付

require 'csv'

n = 0
CSV.open(ARGV.shift, "r") do |row|
  n+=1
end

puts n
teegee:# time ruby test4.rb KEN_ALL.CSV
122493
ruby test4.rb KEN_ALL.CSV  62.80s user 0.25s system 99% cpu 1:03.41 total
teegee:# time ruby test4.rb KEN_ALL.CSV
122493
ruby test4.rb KEN_ALL.CSV  64.91s user 0.24s system 32% cpu 3:22.03 total
teegee:# time ruby test4.rb KEN_ALL.CSV
122493
ruby test4.rb KEN_ALL.CSV  66.57s user 0.25s system 99% cpu 1:07.25 total

fastercsv

csvより早い

require 'fastercsv'

n = 0
FasterCSV.foreach(ARGV.shift) do |row|
  n+=1
end

puts n
teegee:# time ruby test.rb KEN_ALL.CSV
122493
ruby test.rb KEN_ALL.CSV  7.32s user 0.12s system 99% cpu 7.486 total
teegee:# time ruby test.rb KEN_ALL.CSV
122493
ruby test.rb KEN_ALL.CSV  7.36s user 0.12s system 99% cpu 7.522 total
teegee:# time ruby test.rb KEN_ALL.CSV
122493
ruby test.rb KEN_ALL.CSV  8.21s user 0.12s system 99% cpu 8.376 total

lightcsv

csv、fastercsvを改善

require 'lightcsv'

n = 0
LightCsv.foreach(ARGV.shift) do |row|
  n+=1
end

puts n
teegee:# time ruby test3.rb KEN_ALL.CSV
122493
ruby test3.rb KEN_ALL.CSV  4.68s user 0.07s system 99% cpu 4.788 total
teegee:# time ruby test3.rb KEN_ALL.CSV
122493
ruby test3.rb KEN_ALL.CSV  4.82s user 0.08s system 98% cpu 4.993 total
teegee:# time ruby test3.rb KEN_ALL.CSV
122493
ruby test3.rb KEN_ALL.CSV  5.41s user 0.06s system 4% cpu 1:52.53 total

simplecsv

Cライブラリlibcsvを利用した拡張ライブラリ

require 'simplecsv'

n = 0
File.open(ARGV.shift).each do |row|
  SimpleCSV.parse(row) do |r|
    n+=1
  end
end

puts n
teegee:# time ruby test2.rb KEN_ALL.CSV
122493
ruby test2.rb KEN_ALL.CSV  0.83s user 0.04s system 97% cpu 0.893 total
teegee:# time ruby test2.rb KEN_ALL.CSV
122493
ruby test2.rb KEN_ALL.CSV  0.90s user 0.04s system 98% cpu 0.948 total
teegee:# time ruby test2.rb KEN_ALL.CSV
122493
ruby test2.rb KEN_ALL.CSV  0.81s user 0.03s system 98% cpu 0.856 total

csvscan

ステートマシンコンパイラ「Ragel」を利用した拡張ライブラリ

require 'csvscan'

n = 0
open(ARGV.shift) do |f|
  CSVScan.scan(f) do |row|
    n+=1
  end
end
puts n
teegee:# time ruby test5.rb KEN_ALL.CSV
122493
ruby test5.rb KEN_ALL.CSV  0.45s user 0.04s system 98% cpu 0.497 total
teegee:# time ruby test5.rb KEN_ALL.CSV
122493
ruby test5.rb KEN_ALL.CSV  0.45s user 0.04s system 99% cpu 0.500 total
teegee:# time ruby test5.rb KEN_ALL.CSV
122493
ruby test5.rb KEN_ALL.CSV  0.48s user 0.04s system 98% cpu 0.527 total


最速値比較

csv 62.80s
fastercsv 7.32s
lightcsv 4.68s
simplecsv 0.83s
csvscan 0.45s

拡張ライブラリはパワフルだ・・