JuliaMath / Combinatorics.jl

A combinatorics library for Julia
http://juliamath.github.io/Combinatorics.jl/dev/
Other
214 stars 58 forks source link

Improve `factorial(n, k)` performance for `BigInt` #149

Open FedericoStra opened 8 months ago

FedericoStra commented 8 months ago

Use in-place operations from Base.GMP.MPZ to reduce allocations.

With this change I get a massive speed-up, for instance I pass from

julia> @benchmark factorial(big"1000", big"500")
BenchmarkTools.Trial: 10000 samples with 1 evaluation.
 Range (min … max):  100.233 μs … 105.019 ms  ┊ GC (min … max):  0.00% … 80.08%
 Time  (median):     116.240 μs               ┊ GC (median):     0.00%
 Time  (mean ± σ):   259.614 μs ±   2.368 ms  ┊ GC (mean ± σ):  20.95% ±  2.33%

  █▇▇▄▂▁                                                        ▂
  ███████▇▇▇█▅▅▃▃▃▃▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▄ █
  100 μs        Histogram: log(frequency) by time        962 μs <

 Memory estimate: 192.52 KiB, allocs estimate: 3002.

to

julia> @benchmark factorial(big"1000", big"500")
BenchmarkTools.Trial: 10000 samples with 991 evaluations.
 Range (min … max):   49.491 ns … 92.862 μs  ┊ GC (min … max):  0.00% … 52.86%
 Time  (median):      54.742 ns              ┊ GC (median):     0.00%
 Time  (mean ± σ):   110.839 ns ±  2.088 μs  ┊ GC (mean ± σ):  23.97% ±  1.28%

   ▇█▆▁
  ▂█████▆▆▅▃▂▂▃▅▇▆▄▄▃▃▂▂▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▂
  49.5 ns         Histogram: frequency by time          105 ns <

 Memory estimate: 40 bytes, allocs estimate: 2.

for an approximate 2000x performance boost.

codecov[bot] commented 8 months ago

Codecov Report

Attention: 1 lines in your changes are missing coverage. Please review.

Comparison is base (e6888be) 96.97% compared to head (dfb9766) 96.87%.

Files Patch % Lines
src/factorials.jl 87.50% 1 Missing :warning:
Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #149 +/- ## ========================================== - Coverage 96.97% 96.87% -0.11% ========================================== Files 7 7 Lines 728 736 +8 ========================================== + Hits 706 713 +7 - Misses 22 23 +1 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.