Skip to content

Instantly share code, notes, and snippets.

@maierru
Forked from guilhermesimoes/line_count_benchmark.rb
Created August 17, 2018 14:24
Show Gist options
  • Save maierru/de5cdb40d16bec67ca8a2f562d89ad78 to your computer and use it in GitHub Desktop.
Save maierru/de5cdb40d16bec67ca8a2f562d89ad78 to your computer and use it in GitHub Desktop.
Ruby Benchmark: Counting the number of lines of a file
# gem install benchmark-ips
require "benchmark/ips"
path = "lib/rubycritic/cli/options.rb"
Benchmark.ips do |x|
x.report("read + each_line") { File.read(path).each_line.count }
x.report("open + each_line") { File.open(path, "r").each_line.count }
x.report("open + readlines") { File.open(path, "r").readlines.length }
x.report("foreach + count") { File.foreach(path).count }
x.report("foreach + inject") { File.foreach(path).inject(0) {|count, line| count+1} }
x.report("foreach") { count = 0; File.foreach(path) { count+=1}; count }
x.report("wc") { `wc -l < "#{path}"`.to_i }
x.compare!
end
Calculating -------------------------------------
read + each_line 4.272k i/100ms
open + each_line 4.075k i/100ms
open + readlines 4.050k i/100ms
foreach + count 3.569k i/100ms
foreach + inject 2.979k i/100ms
foreach 3.397k i/100ms
wc 26.000 i/100ms
-------------------------------------------------
read + each_line 44.535k (± 2.7%) i/s - 226.416k
open + each_line 42.232k (± 2.7%) i/s - 211.900k
open + readlines 41.585k (± 5.8%) i/s - 210.600k
foreach + count 38.254k (± 1.1%) i/s - 192.726k
foreach + inject 31.478k (± 0.8%) i/s - 157.887k
foreach 35.819k (± 3.2%) i/s - 180.041k
wc 260.809 (± 3.8%) i/s - 1.326k
Comparison:
read + each_line: 44534.7 i/s
open + each_line: 42232.2 i/s - 1.05x slower
open + readlines: 41584.8 i/s - 1.07x slower
foreach + count: 38254.1 i/s - 1.16x slower
foreach: 35818.6 i/s - 1.24x slower
foreach + inject: 31478.2 i/s - 1.41x slower
wc: 260.8 i/s - 170.76x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment