Skip to content

Commit

Permalink
factor::Decomposition: Inline a small number (4) of factors
Browse files Browse the repository at this point in the history
This is ~2% faster, as we do not need to allocate on the heap for most numbers.
  • Loading branch information
nbraud committed Jul 29, 2020
1 parent 3a8cc59 commit 25176ee
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/uu/factor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ num-traits = "0.2" # used in src/numerics.rs, which is included by build.rs
[dependencies]
num-traits = "0.2"
rand = { version="0.7", features=["small_rng"] }
smallvec = "1.4"
uucore = { version="0.0.4", package="uucore", git="https://github.com/uutils/uucore.git", branch="canary" }
uucore_procs = { version="0.0.4", package="uucore_procs", git="https://github.com/uutils/uucore.git", branch="canary" }

Expand Down
10 changes: 8 additions & 2 deletions src/uu/factor/src/factor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

extern crate rand;

use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt;

Expand All @@ -16,11 +17,16 @@ use crate::{miller_rabin, rho, table};
type Exponent = u8;

#[derive(Clone, Debug)]
struct Decomposition(Vec<(u64, Exponent)>);
struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>);

// The number of factors to inline directly into a `Decomposition` object.
// As a consequence of the Erdős–Kac theorem, the average number of prime
// factors of integers < 10²⁵ ≃ 2⁸³ is 4, so we can use that value.
const NUM_FACTORS_INLINE: usize = 4;

impl Decomposition {
fn one() -> Decomposition {
Decomposition(Vec::new())
Decomposition(SmallVec::new())
}

fn add(&mut self, factor: u64, exp: Exponent) {
Expand Down

0 comments on commit 25176ee

Please sign in to comment.