Yiming Jing | cf21fc4 | 2021-07-16 13:23:26 -0700 | [diff] [blame] | 1 | #![feature(test)] |
| 2 | |
| 3 | extern crate test; |
| 4 | |
| 5 | use num_bigint::BigUint; |
| 6 | use num_traits::One; |
| 7 | use std::ops::{Div, Mul}; |
| 8 | use test::Bencher; |
| 9 | |
| 10 | #[bench] |
| 11 | fn factorial_mul_biguint(b: &mut Bencher) { |
| 12 | b.iter(|| { |
| 13 | (1u32..1000) |
| 14 | .map(BigUint::from) |
| 15 | .fold(BigUint::one(), Mul::mul) |
| 16 | }); |
| 17 | } |
| 18 | |
| 19 | #[bench] |
| 20 | fn factorial_mul_u32(b: &mut Bencher) { |
| 21 | b.iter(|| (1u32..1000).fold(BigUint::one(), Mul::mul)); |
| 22 | } |
| 23 | |
| 24 | // The division test is inspired by this blog comparison: |
| 25 | // <https://tiehuis.github.io/big-integers-in-zig#division-test-single-limb> |
| 26 | |
| 27 | #[bench] |
| 28 | fn factorial_div_biguint(b: &mut Bencher) { |
| 29 | let n: BigUint = (1u32..1000).fold(BigUint::one(), Mul::mul); |
| 30 | b.iter(|| { |
| 31 | (1u32..1000) |
| 32 | .rev() |
| 33 | .map(BigUint::from) |
| 34 | .fold(n.clone(), Div::div) |
| 35 | }); |
| 36 | } |
| 37 | |
| 38 | #[bench] |
| 39 | fn factorial_div_u32(b: &mut Bencher) { |
| 40 | let n: BigUint = (1u32..1000).fold(BigUint::one(), Mul::mul); |
| 41 | b.iter(|| (1u32..1000).rev().fold(n.clone(), Div::div)); |
| 42 | } |