From 9e2fc9120e7bc67392e5def09e5a02946bc25174 Mon Sep 17 00:00:00 2001 From: James Miller Date: Mon, 5 Sep 2016 14:57:26 +1200 Subject: [PATCH] Improve performance of Rational::add/sub 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. --- src/rational.rs | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/src/rational.rs b/src/rational.rs index b171ad0bde..4c8c5fb39a 100644 --- a/src/rational.rs +++ b/src/rational.rs @@ -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 { @@ -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);