diff --git a/criterion/Cargo.toml b/criterion/Cargo.toml new file mode 100644 index 00000000..129e6c94 --- /dev/null +++ b/criterion/Cargo.toml @@ -0,0 +1,65 @@ +[package] +description = "Criterion benchmarks for the num-bigint crate" +license = "MIT OR Apache-2.0" +name = "num-bigint-criterion" +version = "0.1.0" +exclude = ["/.github/*"] +edition = "2018" +autobenches = false + +[[bench]] +harness = false +name = "bigint" + +[[bench]] +harness = false +name = "factorial" + +[[bench]] +harness = false +name = "gcd" + +[[bench]] +harness = false +name = "roots" + +[features] +#smallvec = ["num-bigint-small"] +#union = ["num-bigint-small/union"] +default = [] + +[dependencies] +serde_json = "1.0.64" +#ramp = { version = "0.6.0", optional = true } +#rug = { version = "1.12.0", optional = true, features = ["rand"] } +#ibig = { version = "0.3.2", optional = true } +#uint = { version = "0.9.1", optional = true } +#num-bigint-small = { git = "https://github.com/Lemmih/num-bigint", branch = "feature-small-uint", package = "num-bigint", features = ["rand"], optional = true } + +[dependencies.num-integer] +version = "0.1.44" +features = ["i128"] + +#[dependencies.num-bigint] +#version = "0.4.0" +#features = ["rand"] + +[dependencies.num-bigint] +path = ".." +features = ["rand"] + +#[dependencies.num-rational] +#version = "0.4.0" +#git = "https://github.com/Lemmih/num-rational" +#branch = "fewer-clones" + +[dependencies.num-traits] +version = "0.2.14" +features = ["i128"] + +[dependencies.rand] +version = "0.8.4" +default-features = false + +[dev-dependencies] +criterion = "0.3.5" diff --git a/criterion/Criterion.toml b/criterion/Criterion.toml new file mode 100644 index 00000000..1872ecba --- /dev/null +++ b/criterion/Criterion.toml @@ -0,0 +1,3 @@ +output_format = "quiet" +plotting_backend = "disabled" + diff --git a/criterion/LICENSE-APACHE b/criterion/LICENSE-APACHE new file mode 100644 index 00000000..16fe87b0 --- /dev/null +++ b/criterion/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/criterion/LICENSE-MIT b/criterion/LICENSE-MIT new file mode 100644 index 00000000..39d4bdb5 --- /dev/null +++ b/criterion/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/criterion/benches/bigint.rs b/criterion/benches/bigint.rs new file mode 100644 index 00000000..cf009253 --- /dev/null +++ b/criterion/benches/bigint.rs @@ -0,0 +1,323 @@ +use criterion::{criterion_group, criterion_main, Bencher, Criterion}; +#[cfg(not(feature = "smallvec"))] +use num_bigint::{BigInt, BigUint, RandBigInt}; +#[cfg(feature = "smallvec")] +use num_bigint_small::{BigInt, BigUint, RandBigInt}; +use num_traits::{FromPrimitive, Num, One, Zero}; +use std::mem::replace; + +mod rng; +use rng::get_rng; + +fn multiply_bench(b: &mut Bencher, xbits: u64, ybits: u64) { + let mut rng = get_rng(); + let x = rng.gen_bigint(xbits); + let y = rng.gen_bigint(ybits); + + b.iter(|| &x * &y); +} + +fn divide_bench(b: &mut Bencher, xbits: u64, ybits: u64) { + let mut rng = get_rng(); + let x = rng.gen_bigint(xbits); + let y = rng.gen_bigint(ybits); + + b.iter(|| &x / &y); +} + +fn remainder_bench(b: &mut Bencher, xbits: u64, ybits: u64) { + let mut rng = get_rng(); + let x = rng.gen_bigint(xbits); + let y = rng.gen_bigint(ybits); + + b.iter(|| &x % &y); +} + +fn factorial(n: usize) -> BigUint { + let mut f: BigUint = One::one(); + for i in 1..=n { + let bu: BigUint = FromPrimitive::from_usize(i).unwrap(); + f *= bu; + } + f +} + +/// Compute Fibonacci numbers +fn fib(n: usize) -> BigUint { + let mut f0: BigUint = Zero::zero(); + let mut f1: BigUint = One::one(); + for _ in 0..n { + let f2 = f0 + &f1; + f0 = replace(&mut f1, f2); + } + f0 +} + +/// Compute Fibonacci numbers with two ops per iteration +/// (add and subtract, like issue #200) +fn fib2(n: usize) -> BigUint { + let mut f0: BigUint = Zero::zero(); + let mut f1: BigUint = One::one(); + for _ in 0..n { + f1 += &f0; + f0 = &f1 - f0; + } + f0 +} + +fn fib_u128(n: usize) -> u128 { + let mut f0: u128 = Zero::zero(); + let mut f1: u128 = One::one(); + for _ in 0..n { + f1 = f1.checked_add(f0).unwrap(); + f0 = f1.checked_sub(f0).unwrap(); + } + f0 +} + +fn to_str_radix_bench(b: &mut Bencher, radix: u32) { + let mut rng = get_rng(); + let x = rng.gen_bigint(1009); + b.iter(|| x.to_str_radix(radix)); +} + +fn from_str_radix_bench(b: &mut Bencher, radix: u32) { + let mut rng = get_rng(); + let x = rng.gen_bigint(1009); + let s = x.to_str_radix(radix); + assert_eq!(x, BigInt::from_str_radix(&s, radix).unwrap()); + b.iter(|| BigInt::from_str_radix(&s, radix)); +} + +fn rand_bench(b: &mut Bencher, bits: u64) { + let mut rng = get_rng(); + + b.iter(|| rng.gen_bigint(bits)); +} + +/// This modulus is the prime from the 2048-bit MODP DH group: +/// https://tools.ietf.org/html/rfc3526#section-3 +const RFC3526_2048BIT_MODP_GROUP: &str = "\ + FFFFFFFF_FFFFFFFF_C90FDAA2_2168C234_C4C6628B_80DC1CD1\ + 29024E08_8A67CC74_020BBEA6_3B139B22_514A0879_8E3404DD\ + EF9519B3_CD3A431B_302B0A6D_F25F1437_4FE1356D_6D51C245\ + E485B576_625E7EC6_F44C42E9_A637ED6B_0BFF5CB6_F406B7ED\ + EE386BFB_5A899FA5_AE9F2411_7C4B1FE6_49286651_ECE45B3D\ + C2007CB8_A163BF05_98DA4836_1C55D39A_69163FA8_FD24CF5F\ + 83655D23_DCA3AD96_1C62F356_208552BB_9ED52907_7096966D\ + 670C354E_4ABC9804_F1746C08_CA18217C_32905E46_2E36CE3B\ + E39E772C_180E8603_9B2783A2_EC07A28F_B5C55DF0_6F4C52C9\ + DE2BCBF6_95581718_3995497C_EA956AE5_15D22618_98FA0510\ + 15728E5A_8AACAA68_FFFFFFFF_FFFFFFFF"; + +fn criterion_benchmark(c: &mut Criterion) { + { + let mut group = c.benchmark_group("multiply"); + group.bench_function("0", |b| multiply_bench(b, 1 << 8, 1 << 8)); + group.bench_function("1", |b| multiply_bench(b, 1 << 8, 1 << 16)); + group.bench_function("2", |b| multiply_bench(b, 1 << 16, 1 << 16)); + group.bench_function("3", |b| multiply_bench(b, 1 << 16, 1 << 17)); + } + + { + let mut group = c.benchmark_group("divide"); + group.bench_function("0", |b| divide_bench(b, 1 << 8, 1 << 6)); + group.bench_function("1", |b| divide_bench(b, 1 << 12, 1 << 8)); + group.bench_function("2", |b| divide_bench(b, 1 << 16, 1 << 12)); + group.bench_function("big_little", |b| divide_bench(b, 1 << 16, 1 << 4)); + } + + { + let mut group = c.benchmark_group("remainder"); + group.bench_function("0", |b| remainder_bench(b, 1 << 8, 1 << 6)); + group.bench_function("1", |b| remainder_bench(b, 1 << 12, 1 << 8)); + group.bench_function("2", |b| remainder_bench(b, 1 << 16, 1 << 12)); + group.bench_function("big_little", |b| remainder_bench(b, 1 << 16, 1 << 4)); + } + + c.bench_function("factorial_100", |b| b.iter(|| factorial(100))); + + { + let mut group = c.benchmark_group("fib"); + group.bench_function("100", |b| b.iter(|| fib(100))); + group.bench_function("1000", |b| b.iter(|| fib(1000))); + group.bench_function("10000", |b| b.iter(|| fib(10000))); + } + { + let mut group = c.benchmark_group("fib2"); + group.bench_function("100", |b| b.iter(|| fib2(100))); + group.bench_function("1000", |b| b.iter(|| fib2(1000))); + group.bench_function("10000", |b| b.iter(|| fib2(10000))); + } + c.bench_function("fib_u128", |b| b.iter(|| fib_u128(100))); + + c.bench_function("fac_to_string", |b| { + let fac = factorial(100); + b.iter(|| fac.to_string()) + }); + + c.bench_function("fib_to_string", |b| { + let fib = fib(100); + b.iter(|| fib.to_string()); + }); + + { + let mut group = c.benchmark_group("to_str_radix"); + group.bench_function("02", |b| to_str_radix_bench(b, 2)); + group.bench_function("08", |b| to_str_radix_bench(b, 8)); + group.bench_function("10", |b| to_str_radix_bench(b, 10)); + group.bench_function("16", |b| to_str_radix_bench(b, 16)); + group.bench_function("36", |b| to_str_radix_bench(b, 36)); + } + + { + let mut group = c.benchmark_group("from_str_radix"); + group.bench_function("from_str_radix_02", |b| from_str_radix_bench(b, 2)); + group.bench_function("from_str_radix_08", |b| from_str_radix_bench(b, 8)); + group.bench_function("from_str_radix_10", |b| from_str_radix_bench(b, 10)); + group.bench_function("from_str_radix_16", |b| from_str_radix_bench(b, 16)); + group.bench_function("from_str_radix_36", |b| from_str_radix_bench(b, 36)); + } + + { + let mut group = c.benchmark_group("rand"); + group.bench_function("64", |b| rand_bench(b, 1 << 6)); + group.bench_function("256", |b| rand_bench(b, 1 << 8)); + group.bench_function("1009", |b| rand_bench(b, 1009)); + group.bench_function("2048", |b| rand_bench(b, 1 << 11)); + group.bench_function("4096", |b| rand_bench(b, 1 << 12)); + group.bench_function("8192", |b| rand_bench(b, 1 << 13)); + group.bench_function("65536", |b| rand_bench(b, 1 << 16)); + group.bench_function("131072", |b| rand_bench(b, 1 << 17)); + } + + c.bench_function("shl", |b| { + let n = BigUint::one() << 1000u32; + let mut m = n.clone(); + b.iter(|| { + m.clone_from(&n); + for i in 0..50 { + m <<= i; + } + }) + }); + + c.bench_function("shr", |b| { + let n = BigUint::one() << 2000u32; + let mut m = n.clone(); + b.iter(|| { + m.clone_from(&n); + for i in 0..50 { + m >>= i; + } + }) + }); + + c.bench_function("hahs", |b| { + use std::collections::HashSet; + let mut rng = get_rng(); + let v: Vec = (1000..2000).map(|bits| rng.gen_bigint(bits)).collect(); + b.iter(|| { + let h: HashSet<&BigInt> = v.iter().collect(); + assert_eq!(h.len(), v.len()); + }); + }); + + c.bench_function("pow_bench", |b| { + b.iter(|| { + let upper = 100_u32; + let mut i_big = BigUint::from(1u32); + for _i in 2..=upper { + i_big += 1u32; + for j in 2..=upper { + i_big.pow(j); + } + } + }); + }); + + { + let mut group = c.benchmark_group("pow"); + group.bench_function("pow_bench_bigexp", |b| { + use num_traits::Pow; + + b.iter(|| { + let upper = 100_u32; + let mut i_big = BigUint::from(1u32); + for _i in 2..=upper { + i_big += 1u32; + let mut j_big = BigUint::from(1u32); + for _j in 2..=upper { + j_big += 1u32; + Pow::pow(&i_big, &j_big); + } + } + }); + }); + + group.bench_function("1e1000", |b| { + b.iter(|| BigUint::from(10u32).pow(1_000)); + }); + + group.bench_function("1e10000", |b| { + b.iter(|| BigUint::from(10u32).pow(10_000)); + }); + + group.bench_function("1e100000", |b| { + b.iter(|| BigUint::from(10u32).pow(100_000)); + }); + + group.bench_function("modpow", |b| { + let mut rng = get_rng(); + let base = rng.gen_biguint(2048); + let e = rng.gen_biguint(2048); + let m = BigUint::from_str_radix(RFC3526_2048BIT_MODP_GROUP, 16).unwrap(); + + b.iter(|| base.modpow(&e, &m)); + }); + + group.bench_function("modpow_even", |b| { + let mut rng = get_rng(); + let base = rng.gen_biguint(2048); + let e = rng.gen_biguint(2048); + // Make the modulus even, so monty (base-2^32) doesn't apply. + let m = BigUint::from_str_radix(RFC3526_2048BIT_MODP_GROUP, 16).unwrap() - 1u32; + + b.iter(|| base.modpow(&e, &m)); + }); + } + + { + let mut group = c.benchmark_group("iters"); + group.bench_function("to_u32_digits", |b| { + let mut rng = get_rng(); + let n = rng.gen_biguint(2048); + + b.iter(|| n.to_u32_digits()); + }); + + group.bench_function("iter_u32_digits", |b| { + let mut rng = get_rng(); + let n = rng.gen_biguint(2048); + + b.iter(|| n.iter_u32_digits().max()); + }); + + group.bench_function("to_u64_digits", |b| { + let mut rng = get_rng(); + let n = rng.gen_biguint(2048); + + b.iter(|| n.to_u64_digits()); + }); + + group.bench_function("iter_u64_digits", |b| { + let mut rng = get_rng(); + let n = rng.gen_biguint(2048); + + b.iter(|| n.iter_u64_digits().max()); + }); + } +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/criterion/benches/factorial.rs b/criterion/benches/factorial.rs new file mode 100644 index 00000000..ddacfb8c --- /dev/null +++ b/criterion/benches/factorial.rs @@ -0,0 +1,41 @@ +use criterion::{criterion_group, criterion_main, Criterion}; + +use num_bigint::BigUint; +use num_traits::One; +use std::ops::{Div, Mul}; + +fn criterion_benchmark(c: &mut Criterion) { + let mut group = c.benchmark_group("factorial"); + group.bench_function("mul_biguint", |b| { + b.iter(|| { + (1u32..1000) + .map(BigUint::from) + .fold(BigUint::one(), Mul::mul) + }); + }); + + group.bench_function("mul_u32", |b| { + b.iter(|| (1u32..1000).fold(BigUint::one(), Mul::mul)); + }); + + // The division test is inspired by this blog comparison: + // + + group.bench_function("div_biguint", |b| { + let n: BigUint = (1u32..1000).fold(BigUint::one(), Mul::mul); + b.iter(|| { + (1u32..1000) + .rev() + .map(BigUint::from) + .fold(n.clone(), Div::div) + }); + }); + + group.bench_function("div_u32", |b| { + let n: BigUint = (1u32..1000).fold(BigUint::one(), Mul::mul); + b.iter(|| (1u32..1000).rev().fold(n.clone(), Div::div)); + }); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/criterion/benches/gcd.rs b/criterion/benches/gcd.rs new file mode 100644 index 00000000..85caecd2 --- /dev/null +++ b/criterion/benches/gcd.rs @@ -0,0 +1,51 @@ +use criterion::{criterion_group, criterion_main, Bencher, Criterion}; + +use num_bigint::{BigUint, RandBigInt}; +use num_integer::Integer; +use num_traits::Zero; + +mod rng; +use rng::get_rng; + +fn bench(b: &mut Bencher, bits: u64, gcd: fn(&BigUint, &BigUint) -> BigUint) { + let mut rng = get_rng(); + let x = rng.gen_biguint(bits); + let y = rng.gen_biguint(bits); + + assert_eq!(euclid(&x, &y), x.gcd(&y)); + + b.iter(|| gcd(&x, &y)); +} + +fn euclid(x: &BigUint, y: &BigUint) -> BigUint { + // Use Euclid's algorithm + let mut m = x.clone(); + let mut n = y.clone(); + while !m.is_zero() { + let temp = m; + m = n % &temp; + n = temp; + } + n +} + +fn criterion_benchmark(c: &mut Criterion) { + { + let mut group = c.benchmark_group("gcd_euclid"); + group.bench_function("0064", |b| bench(b, 64, euclid)); + group.bench_function("0256", |b| bench(b, 256, euclid)); + group.bench_function("1024", |b| bench(b, 1024, euclid)); + group.bench_function("4096", |b| bench(b, 4096, euclid)); + } + + { + let mut group = c.benchmark_group("gcd_stein"); + group.bench_function("0064", |b| bench(b, 64, BigUint::gcd)); + group.bench_function("0256", |b| bench(b, 256, BigUint::gcd)); + group.bench_function("1024", |b| bench(b, 1024, BigUint::gcd)); + group.bench_function("4096", |b| bench(b, 4096, BigUint::gcd)); + } +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/criterion/benches/rng/mod.rs b/criterion/benches/rng/mod.rs new file mode 100644 index 00000000..33e4f0fa --- /dev/null +++ b/criterion/benches/rng/mod.rs @@ -0,0 +1,38 @@ +use rand::RngCore; + +pub(crate) fn get_rng() -> impl RngCore { + XorShiftStar { + a: 0x0123_4567_89AB_CDEF, + } +} + +/// Simple `Rng` for benchmarking without additional dependencies +struct XorShiftStar { + a: u64, +} + +impl RngCore for XorShiftStar { + fn next_u32(&mut self) -> u32 { + self.next_u64() as u32 + } + + fn next_u64(&mut self) -> u64 { + // https://en.wikipedia.org/wiki/Xorshift#xorshift* + self.a ^= self.a >> 12; + self.a ^= self.a << 25; + self.a ^= self.a >> 27; + self.a.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + for chunk in dest.chunks_mut(8) { + let bytes = self.next_u64().to_le_bytes(); + let slice = &bytes[..chunk.len()]; + chunk.copy_from_slice(slice) + } + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { + Ok(self.fill_bytes(dest)) + } +} diff --git a/criterion/benches/roots.rs b/criterion/benches/roots.rs new file mode 100644 index 00000000..c0204edf --- /dev/null +++ b/criterion/benches/roots.rs @@ -0,0 +1,103 @@ +use criterion::{criterion_group, criterion_main, Bencher, Criterion}; + +use num_bigint::{BigUint, RandBigInt}; + +mod rng; +use rng::get_rng; + +// The `big64` cases demonstrate the speed of cases where the value +// can be converted to a `u64` primitive for faster calculation. +// +// The `big1k` cases demonstrate those that can convert to `f64` for +// a better initial guess of the actual value. +// +// The `big2k` and `big4k` cases are too big for `f64`, and use a simpler guess. + +fn check(x: &BigUint, n: u32) { + let root = x.nth_root(n); + if n == 2 { + assert_eq!(root, x.sqrt()) + } else if n == 3 { + assert_eq!(root, x.cbrt()) + } + + let lo = root.pow(n); + assert!(lo <= *x); + assert_eq!(lo.nth_root(n), root); + assert_eq!((&lo - 1u32).nth_root(n), &root - 1u32); + + let hi = (&root + 1u32).pow(n); + assert!(hi > *x); + assert_eq!(hi.nth_root(n), &root + 1u32); + assert_eq!((&hi - 1u32).nth_root(n), root); +} + +fn bench_sqrt(b: &mut Bencher, bits: u64) { + let x = get_rng().gen_biguint(bits); + // eprintln!("bench_sqrt({})", x); + + check(&x, 2); + b.iter(|| x.sqrt()); +} + +fn bench_nth_root(b: &mut Bencher, bits: u64, n: u32) { + let x = get_rng().gen_biguint(bits); + // eprintln!("bench_{}th_root({})", n, x); + + check(&x, n); + b.iter(|| x.nth_root(n)); +} + +fn bench_cbrt(b: &mut Bencher, bits: u64) { + let x = get_rng().gen_biguint(bits); + // eprintln!("bench_cbrt({})", x); + + check(&x, 3); + b.iter(|| x.cbrt()); +} + +fn criterion_benchmark(c: &mut Criterion) { + { + let mut group = c.benchmark_group("sqrt"); + group.bench_function("64", |b| bench_sqrt(b, 64)); + group.bench_function("1k", |b| bench_sqrt(b, 1024)); + group.bench_function("2k", |b| bench_sqrt(b, 2048)); + group.bench_function("4k", |b| bench_sqrt(b, 4096)); + } + + { + let mut group = c.benchmark_group("cbrt"); + group.bench_function("64", |b| bench_cbrt(b, 64)); + group.bench_function("1k", |b| bench_cbrt(b, 1024)); + group.bench_function("2k", |b| bench_cbrt(b, 2048)); + group.bench_function("4k", |b| bench_cbrt(b, 4096)); + } + + { + let mut group = c.benchmark_group("cbrt"); + group.bench_function("64_nth_10", |b| bench_nth_root(b, 64, 10)); + group.bench_function("1k_nth_10", |b| bench_nth_root(b, 1024, 10)); + group.bench_function("1k_nth_100", |b| bench_nth_root(b, 1024, 100)); + group.bench_function("1k_nth_1000", |b| bench_nth_root(b, 1024, 1000)); + group.bench_function("1k_nth_10000", |b| bench_nth_root(b, 1024, 10000)); + } + + { + let mut group = c.benchmark_group("cbrt"); + group.bench_function("2k_nth_10", |b| bench_nth_root(b, 2048, 10)); + group.bench_function("2k_nth_100", |b| bench_nth_root(b, 2048, 100)); + group.bench_function("2k_nth_1000", |b| bench_nth_root(b, 2048, 1000)); + group.bench_function("2k_nth_10000", |b| bench_nth_root(b, 2048, 10000)); + } + + { + let mut group = c.benchmark_group("cbrt"); + group.bench_function("4k_nth_10", |b| bench_nth_root(b, 4096, 10)); + group.bench_function("4k_nth_100", |b| bench_nth_root(b, 4096, 100)); + group.bench_function("4k_nth_1000", |b| bench_nth_root(b, 4096, 1000)); + group.bench_function("4k_nth_10000", |b| bench_nth_root(b, 4096, 10000)); + } +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/criterion/src/bin/shootout-pidigits.rs b/criterion/src/bin/shootout-pidigits.rs new file mode 100644 index 00000000..b95d42cc --- /dev/null +++ b/criterion/src/bin/shootout-pidigits.rs @@ -0,0 +1,138 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers + +// Copyright (c) 2013-2014 The Rust Project Developers +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// - Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in +// the documentation and/or other materials provided with the +// distribution. +// +// - Neither the name of "The Computer Language Benchmarks Game" nor +// the name of "The Computer Language Shootout Benchmarks" nor the +// names of its contributors may be used to endorse or promote +// products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + +use std::io; +use std::str::FromStr; + +use num_bigint::BigInt; +use num_integer::Integer; +use num_traits::{FromPrimitive, One, ToPrimitive, Zero}; + +struct Context { + numer: BigInt, + accum: BigInt, + denom: BigInt, +} + +impl Context { + fn new() -> Context { + Context { + numer: One::one(), + accum: Zero::zero(), + denom: One::one(), + } + } + + fn from_i32(i: i32) -> BigInt { + FromPrimitive::from_i32(i).unwrap() + } + + fn extract_digit(&self) -> i32 { + if self.numer > self.accum { + return -1; + } + let (q, r) = (&self.numer * Context::from_i32(3) + &self.accum).div_rem(&self.denom); + if r + &self.numer >= self.denom { + return -1; + } + q.to_i32().unwrap() + } + + fn next_term(&mut self, k: i32) { + let y2 = Context::from_i32(k * 2 + 1); + self.accum = (&self.accum + (&self.numer << 1)) * &y2; + self.numer = &self.numer * Context::from_i32(k); + self.denom = &self.denom * y2; + } + + fn eliminate_digit(&mut self, d: i32) { + let d = Context::from_i32(d); + let ten = Context::from_i32(10); + self.accum = (&self.accum - &self.denom * d) * &ten; + self.numer = &self.numer * ten; + } +} + +fn pidigits(n: isize, out: &mut dyn io::Write) -> io::Result<()> { + let mut k = 0; + let mut context = Context::new(); + + for i in 1..=n { + let mut d; + loop { + k += 1; + context.next_term(k); + d = context.extract_digit(); + if d != -1 { + break; + } + } + + write!(out, "{}", d)?; + if i % 10 == 0 { + writeln!(out, "\t:{}", i)?; + } + + context.eliminate_digit(d); + } + + let m = n % 10; + if m != 0 { + for _ in m..10 { + write!(out, " ")?; + } + writeln!(out, "\t:{}", n)?; + } + Ok(()) +} + +const DEFAULT_DIGITS: isize = 512; + +fn main() { + let args = std::env::args().collect::>(); + let n = if args.len() < 2 { + DEFAULT_DIGITS + } else if args[1] == "--bench" { + return pidigits(DEFAULT_DIGITS, &mut std::io::sink()).unwrap(); + } else { + FromStr::from_str(&args[1]).unwrap() + }; + pidigits(n, &mut std::io::stdout()).unwrap(); +}