Project

General

Profile

Actions

Feature #5378

closed

Prime.each is slow

Added by mconigliaro (Mike Conigliaro) over 12 years ago. Updated over 2 years ago.

Status:
Closed
Target version:
-
[ruby-core:39769]

Description

See discussion here: https://gist.github.com/1246868

require 'benchmark'
require 'prime'

def primes_up_to(n)
s = [nil, nil] + (2..n).to_a
(2..(n ** 0.5).to_i).reject { |i| s[i].nil? }.each do |i|
(i ** 2).step(n, i) { |j| s[j] = nil }
end
s.compact
end

Benchmark.bm(12) do |x|
x.report('primes_up_to') { primes_up_to(2000000).inject(0) { |memo,obj| memo + obj } }
x.report('Prime.each') { Prime.each(2000000).inject(0) { |memo,obj| memo + obj } }
end

$ ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin10.8.0]
$ ruby lol.rb
user system total real
primes_up_to 1.470000 0.020000 1.490000 ( 1.491340)
Prime.each 7.820000 0.010000 7.830000 ( 7.820969)


Files

prime.patch (4.06 KB) prime.patch h.shirosaki (Hiroshi Shirosaki), 10/01/2011 03:26 PM

Related issues 1 (0 open1 closed)

Has duplicate Ruby master - Feature #10354: Optimize Integer#prime?Closedyugui (Yuki Sonoda)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0