Skip to content

Instantly share code, notes, and snippets.

@hanachin
Last active December 5, 2018 14:27
Show Gist options
  • Save hanachin/b9143a6cab020515b3fc636c8be985a2 to your computer and use it in GitHub Desktop.
Save hanachin/b9143a6cab020515b3fc636c8be985a2 to your computer and use it in GitHub Desktop.
Re: シクシク素数アドベントカレンダー Ruby 編 ref: https://qiita.com/hanachin_/items/ac842237556d0a1d5a1b
require 'prime'
😭prime = Prime.each.lazy.select {|prime|
digits = prime.digits
digits.include?(4) || digits.include?(9)
}
puts 😭prime.take(ARGV.first.to_i).to_a.join(",")
require 'benchmark_driver'
Benchmark.driver do |x|
x.prelude <<~RUBY
require 'prime'
😭prime = Enumerator.new do |y|
a = 1
loop do
a += 1
loop { a.prime? && a.to_s.match(/[49]/) ? break : a += 1 }
y << a
end
end
😭prime.take(100)
😭prime2 = Prime.each.lazy.select {|prime|
digits = prime.digits
digits.include?(4) || digits.include?(9)
}
😭prime2.take(100)
RUBY
x.report 'tbpgr', '😭prime.take(100)'
x.report 'hanachin', '😭prime2.take(100).to_a'
end
% ruby -v /tmp/49.rb
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-linux]
Warming up --------------------------------------
tbpgr 1.871k i/s - 1.880k times in 1.004923s (534.53μs/i)
hanachin 4.642k i/s - 4.972k times in 1.071051s (215.42μs/i)
Calculating -------------------------------------
tbpgr 1.958k i/s - 5.612k times in 2.866668s (510.81μs/i)
hanachin 4.593k i/s - 13.926k times in 3.032325s (217.75μs/i)
Comparison:
hanachin: 4592.5 i/s
tbpgr: 1957.7 i/s - 2.35x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment