diff options
author | Kouhei Yanagita <[email protected]> | 2022-07-22 12:05:16 +0900 |
---|---|---|
committer | Yusuke Endoh <[email protected]> | 2022-08-12 15:57:52 +0900 |
commit | 803a07263001e5466bba0f53fcc85784f4b5c686 (patch) | |
tree | 75e93f8d4f8aad0c5038f03f0214efd6ae190e52 /numeric.rb | |
parent | 24e33b84b5adb29d1d2f541acfba65e225b91b55 (diff) |
Improve performance of Integer#ceildiv
This patch is suggested by nobu.
Benchmark result:
```
require 'benchmark'
n = 10 ** 7
Benchmark.bm do |x|
x.report("Fixnum/Fixnum") { a, b = 5, 2; n.times { a.ceildiv(b) } }
x.report("Bignum/Bignum") { a, b = 10**100, 10**99 - 1; n.times { a.ceildiv(b) } }
x.report("Bignum/Fixnum") { a, b = 10**100, 3; n.times { a.ceildiv(b) } }
end
```
Original:
```
user system total real
Fixnum/Fixnum 3.340009 0.043029 3.383038 ( 3.384022)
Bignum/Bignum 8.229500 0.118543 8.348043 ( 8.349574)
Bignum/Fixnum 8.328971 0.097842 8.426813 ( 8.426952)
```
Improved:
```
user system total real
Fixnum/Fixnum 0.699140 0.000961 0.700101 ( 0.700199)
Bignum/Bignum 5.076165 0.083160 5.159325 ( 5.159360)
Bignum/Fixnum 5.548684 0.115372 5.664056 ( 5.666735)
```
Notes
Notes:
Merged: https://github.com/ruby/ruby/pull/5965
Diffstat (limited to 'numeric.rb')
-rw-r--r-- | numeric.rb | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/numeric.rb b/numeric.rb index 9f2200d2a8..c2091465f8 100644 --- a/numeric.rb +++ b/numeric.rb @@ -227,6 +227,23 @@ class Integer Primitive.attr! 'inline' Primitive.cexpr! 'rb_int_zero_p(self)' end + + # call-seq: + # ceildiv(other) -> integer + # + # Returns the result of division +self+ by +other+. The result is rounded up to the nearest integer. + # + # 3.ceildiv(3) # => 1 + # 4.ceildiv(3) # => 2 + # + # 4.ceildiv(-3) # => -1 + # -4.ceildiv(3) # => -1 + # -4.ceildiv(-3) # => 2 + # + # 3.ceildiv(1.2) # => 3 + def ceildiv(other) + -div(-other) + end end # call-seq: |