gmpxx patch: remove some copying

Marc Glisse marc.glisse at
Tue Sep 2 18:20:39 CEST 2008


a small (3 lines) patch proposition and associated changelog entry. This 
is a performance patch, so not for 4.2.*.

 	* gmpxx.h (__gmp_set_expr): Remove useless copy in assignment of
 	integer expr to rational.
 	* gmpxx.h: Evaluate unary operations in-place for compound

The first part depends on the recent __gmp_set_expr fix I sent (this is 
actually how I discovered the issue).


1) to assign an expression that yields an integer to a rational, the 
current code computes the integer in a temporary and assigns it to the 
rational. I change this to compute the integer in the numerator of the 
rational (and set the denominator to 1). This means one less copy.

2) to compute a=-(c+d), the current code does temp=c+d, a=-temp. I change 
it to a=c+d, a=-a (in-place operation). As far as I can see, sqrt is the 
only function which is slower in-place, and I don't think it is worth 
making a special case for it. I am not changing the mpf case because it 
might interfere with the way the precision is set (I am not sure so I 
don't want to take risks).

Any comment?

Marc Glisse
-------------- next part --------------
--- /home/glisse/aout/gmpxx.h	2008-08-01 16:44:18.000000000 +0200
+++ gmpxx.h	2008-09-01 15:16:13.000000000 +0200
@@ -2158,8 +2158,8 @@
 template <class T>
 inline void __gmp_set_expr(mpq_ptr q, const __gmp_expr<mpz_t, T> &expr)
-  mpz_class temp(expr);
-  mpq_set_z(q, temp.get_mpz_t());
+  expr.eval(mpq_numref(q));
+  mpz_set_ui(mpq_denref(q),1);
 template <>
@@ -2274,10 +2274,10 @@
   __gmp_expr(const val_type &val) : expr(val) { }
   void eval(typename __gmp_resolve_expr<T>::ptr_type p) const
-  { __gmp_expr<T, T> temp(expr.val); Op::eval(p, temp.__get_mp()); }
+  { expr.val.eval(p); Op::eval(p, p); }
   void eval(typename __gmp_resolve_expr<T>::ptr_type p,
 	    unsigned long int prec) const
   { __gmp_expr<T, T> temp(expr.val, prec); Op::eval(p, temp.__get_mp()); }

More information about the gmp-bugs mailing list