Skip to content

Instantly share code, notes, and snippets.

@kojix2
Last active June 10, 2021 10:32
Show Gist options
  • Save kojix2/0d9d8ada2aa63f09fba5438ca77862f6 to your computer and use it in GitHub Desktop.
Save kojix2/0d9d8ada2aa63f09fba5438ca77862f6 to your computer and use it in GitHub Desktop.
require 'benchmark_driver'
Benchmark.driver do |x|
x.prelude <<~RUBY
require 'numo/narray'
require 'prime'
class Integer
def devisors
[1].product(*prime_division.map { |p, n| (0..n).map { p**_1 } }).map { _1.inject(:*) }.sort
end
def devisors_na
r = Math.sqrt(self)
a = Numo::UInt32.new(r).seq + 1
b = a.new_fill(self)
c = a[(b % a).eq(0)]
d = (self / c).reverse
if r.to_i == r
c.to_a.concat d[1..-1].to_a
else
c.to_a.concat d.to_a
end
end
end
RUBY
x.report 'devisors', %( 9699690.devisors )
x.report 'devisors_narray', %( 9699690.devisors_na )
end
# Warming up --------------------------------------
# devisors 8.172k i/s - 8.470k times in 1.036435s (122.37μs/i)
# devisors_narray 24.835k i/s - 26.675k times in 1.074069s (40.27μs/i)
# Calculating -------------------------------------
# devisors 8.392k i/s - 24.516k times in 2.921366s (119.16μs/i)
# devisors_narray 24.816k i/s - 74.506k times in 3.002390s (40.30μs/i)
#
# Comparison:
# devisors_narray: 24815.6 i/s
# devisors: 8392.0 i/s - 2.96x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment