Forked from guilhermesimoes/line_count_benchmark.rb
Last active
June 9, 2017 03:29
-
-
Save Domon/44240448b1db168016525bbfaf0b33d1 to your computer and use it in GitHub Desktop.
Ruby Benchmark: Counting the number of lines of a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# gem install benchmark-ips | |
require "benchmark/ips" | |
path = "path/to/a_big_file" | |
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Warming up -------------------------------------- | |
read + each_line 1.000 i/100ms | |
open + each_line 1.000 i/100ms | |
open + readlines 1.000 i/100ms | |
foreach + count 1.000 i/100ms | |
foreach + inject 1.000 i/100ms | |
foreach 1.000 i/100ms | |
wc 1.000 i/100ms | |
Calculating ------------------------------------- | |
read + each_line 1.341 (± 0.0%) i/s - 7.000 in 5.231149s | |
open + each_line 1.730 (± 0.0%) i/s - 9.000 in 5.206121s | |
open + readlines 1.402 (± 0.0%) i/s - 7.000 in 5.025912s | |
foreach + count 1.598 (± 0.0%) i/s - 9.000 in 5.635684s | |
foreach + inject 1.468 (± 0.0%) i/s - 8.000 in 5.453793s | |
foreach 1.486 (± 0.0%) i/s - 8.000 in 5.386620s | |
wc 3.446 (± 0.0%) i/s - 18.000 in 5.226358s | |
Comparison: | |
wc: 3.4 i/s | |
open + each_line: 1.7 i/s - 1.99x slower | |
foreach + count: 1.6 i/s - 2.16x slower | |
foreach: 1.5 i/s - 2.32x slower | |
foreach + inject: 1.5 i/s - 2.35x slower | |
open + readlines: 1.4 i/s - 2.46x slower | |
read + each_line: 1.3 i/s - 2.57x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment