Skip to content

Instantly share code, notes, and snippets.

@athityakumar
Created May 21, 2017 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save athityakumar/351d03d6ad63a37f05e8f41514248b3f to your computer and use it in GitHub Desktop.
Save athityakumar/351d03d6ad63a37f05e8f41514248b3f to your computer and use it in GitHub Desktop.
Benchmarking gems for parsing from and writing to CSV files.
require 'benchmark'
require 'csv'
require 'rcsv'
module Compare
module Core
class << self
def new
@rows = 1000
@cols = 1000
@grid = Array.new(@rows) { Array.new(@cols) { |index| index} }
@file = "sample.csv"
sample_csv_file
Importer.compare @file
Exporter.compare @grid
end
def sample_csv_file
File.delete @file if File.exists? @file
CSV.open(@file, "w") do |csv|
@grid.each do |row|
csv << row
end
end
end
end
end
module Importer
class << self
def compare file
@file = file
puts "\nImporter module comparisions"
Benchmark.bm(10) do |x|
x.report('stdlib csv:') { csv }
x.report('rcsv gem:') { rcsv }
end
end
def csv
CSV.read @file
end
def rcsv
Rcsv.parse File.open(@file)
end
end
end
module Exporter
class << self
def compare grid
@grid = grid
puts "\nExporter module comparisions"
Benchmark.bm(10) do |x|
x.report('stdlib csv:') { csv }
x.report('rcsv gem:') { rcsv }
end
end
def csv
CSV.open("csv.csv", "w") do |csv|
@grid.each do |row|
csv << row
end
end
end
def rcsv
writer = Rcsv.new
io = StringIO.new
writer.write(io) do
@grid.shift
end
File.open("rcsv.csv", "w") { |file| file.write io.string }
end
end
end
end
Compare::Core.new
# Importer module comparisions
# user system total real
# stdlib csv: 0.970000 0.050000 1.020000 ( 1.037277)
# rcsv gem: 0.170000 0.020000 0.190000 ( 0.214649)
#
# Exporter module comparisions
# user system total real
# stdlib csv: 1.380000 0.040000 1.420000 ( 1.441838)
# rcsv gem: 1.170000 0.030000 1.200000 ( 1.246726)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment