mpz_addmul_ui with ui = 1

Roberto Bagnara bagnara at
Wed Jan 28 13:55:06 CET 2009

Jim White wrote:
> I have a loop that spends 99+% of its time executing these two statements:
>       mpz_addmul_ui(BB, B, a);
>       mpz_swap     (B, BB);
> To my surprise, it runs 25% faster if I replace it with:
>       if (a==1) mpz_add      (BB, B, BB);
>       else      mpz_addmul_ui(BB, B, a);
>       mpz_swap(B, BB);
> It's an RCF (regular continued-fraction) algorithm, so a=1 about 41.5% of the time.  
> No big deal, but perhaps in future revs  mpz_addmul_ui and its sister function might auto-detect this case and reroute the call?

In the Parma Polyhedra Library, we found out that,
for mpz_mul(), checking the source arguments against 0
gives rise to significant speedups in some algorithms.

We thought (but we are not sure) that this is indeed
a feature, and not a limitation: since only the client
code can know about the frequence of special cases,
let the client code take the decision.  The alternative
would be that GMP does a lot of checks that are possibly
useless, perhaps duplicating work that has already been
done by the client code.

I am glad you raised the issue here and I hope Torbjorn
will correct me if I misinterpreted the GMP's policies
in this respect.
All the best,


Prof. Roberto Bagnara
Computer Science Group
Department of Mathematics, University of Parma, Italy
mailto:bagnara at

More information about the gmp-discuss mailing list