Skip to content

Commit

Permalink
Improve performance of Rational::add/sub
Browse files Browse the repository at this point in the history
GCD calculation is quite slow (See #73), and using it to find a common
denominator causes a massive slowdown for addition and subtraction.
Replace it with a naive function that just mulitplies the two original
denominators together to find a common denominator.
  • Loading branch information
Aatch committed Sep 5, 2016
1 parent 80b31c7 commit 9e2fc91
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions src/rational.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,17 +361,19 @@ fn make_common_denominator(a: &mut Rational, b: &mut Rational) {
return;
}

let gcd = a.d.gcd(&b.d);
let lcm = (&a.d * &b.d) / &gcd;
// FIXME #73: GCD is currently very slow, so a simpler
// calculation that just multiplies the denominators together
// is faster. This is logically the same as having GCD = 1

//let gcd = a.d.gcd(&b.d);
let lcm = &a.d * &b.d;

if lcm != a.d {
a.n *= &b.d;
a.n /= &gcd;
}

if lcm != b.d {
b.n *= &a.d;
b.n /= gcd;
}

if lcm != a.d {
Expand Down Expand Up @@ -1179,6 +1181,35 @@ mod test {
});
}

#[bench]
fn bench_add_5(b: &mut Bencher) {
let r1 = rand_rational(20);
let r2 = rand_rational(20);
let r3 = rand_rational(20);
let r4 = rand_rational(20);
let r5 = rand_rational(20);

b.iter(|| {
let x = &r1 + &r2 + &r3 + &r4 + &r5;
test::black_box(x);
});
}

#[bench]
fn bench_add_5_normalize(b: &mut Bencher) {
let r1 = rand_rational(20);
let r2 = rand_rational(20);
let r3 = rand_rational(20);
let r4 = rand_rational(20);
let r5 = rand_rational(20);

b.iter(|| {
let mut x = &r1 + &r2 + &r3 + &r4 + &r5;
x.normalize();
test::black_box(x);
});
}

#[bench]
fn bench_sub(b: &mut Bencher) {
let x = rand_rational(20);
Expand Down

0 comments on commit 9e2fc91

Please sign in to comment.