Skip to content

Commit

Permalink
Optimize bignum * 2^n case
Browse files Browse the repository at this point in the history
  • Loading branch information
shirok committed Oct 27, 2023
1 parent a955026 commit 29f00c7
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
5 changes: 5 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
2023-10-26 Shiro Kawai <shiro@acm.org>

* src/bignum.c (bignum_mul_si): Optimize special case when bignum
muliplied by y=2^n (y is fixnum).

2023-10-24 Shiro Kawai <shiro@acm.org>

* lib/r7rs-setup.scm (open-binary-*-file): Even though Gauche
Expand Down
16 changes: 11 additions & 5 deletions src/bignum.c
Original file line number Diff line number Diff line change
Expand Up @@ -814,13 +814,19 @@ static ScmBignum *bignum_mul_si(const ScmBignum *bx, long y)
br->sign = -br->sign;
return br;
}
/* TODO: optimize for 2^n case !*/
ScmBignum *br;
br = make_bignum(bx->size + 1); /* TODO: more accurate estimation */
u_long yabs = (y<0)? -y:y;
br->sign = bx->sign;
bignum_mul_word(br, bx, yabs, 0);
if (y<0) br->sign = -br->sign;
if (y & (y-1)) {
/* general case */
u_long yabs = (y<0)? -y:y;
br->sign = bx->sign;
bignum_mul_word(br, bx, yabs, 0);
if (y<0) br->sign = -br->sign;
} else {
/* fast path when y is a power of two (note that y != 0). */
int n = Scm__LowestBitNumber((u_long)y);
bignum_lshift(br, bx, n);
}
return br;
}

Expand Down
11 changes: 11 additions & 0 deletions test/number.scm
Original file line number Diff line number Diff line change
Expand Up @@ -1488,6 +1488,17 @@
(test* "0.0 * bignum" 0.0 (Apply * `(0.0 ,big)) eqv?)
(test* "bignum * 1.0" 1.0e20 (Apply * `(,big 1.0)) eqv?)
(test* "1.0 * bignum" 1.0e20 (Apply * `(1.0 ,big)) eqv?)

;; 2^n shortcut
(dotimes [n 64]
(test* (format "bignum * 2^~a" n)
(ash big n)
(Apply * `(,big ,(expt 2 n)))
eqv?)
(test* (format "2^~a & bignum" n)
(ash big n)
(Apply * `(,(expt 2 n) ,big))
eqv?))
)

(test* "ratnum * 0" 0 (Apply * '(1/2 0)) eqv?)
Expand Down

0 comments on commit 29f00c7

Please sign in to comment.