speed of mpq_cmp vs mpq_sub
Marc Glisse
marc.glisse at inria.fr
Sun May 22 09:10:58 UTC 2016
Hello,
in http://stackoverflow.com/q/37366527/1918193 , someone noticed that
calling mpq_cmp can, in some cases like comparing 2 equal numbers, be much
slower (10 times or more) than calling mpq_sub and checking the sign of
the result. With the program below, no macro defined, it takes 1.4s. With
-DSLOW (use cmp instead of sub) it jumps to 23.8s. On the other hand, if I
define DIFF so that the denominators are different, the version with cmp
keeps roughly the same performance, while the version with sub takes
35.6s. I am not sure we should change anything, but I was surprised at how
much the cost of the cmp operation could dwarf the rest of the
computations in that stackoverflow post (you can replace mpq_rational
with mpq_class from gmpxx.h if you want to test that code).
#include <gmp.h>
int main(){
mpq_t x;
mpq_t y;
mpq_t z;
mpq_init(x);
mpq_init(y);
mpq_init(z);
mpq_set_d(x,1.037);
volatile int b;
for(int i=0;i<20;++i) mpq_mul(x,x,x);
mpq_set(y,x);
#ifdef DIFF
mpz_add_ui(mpq_denref(y),mpq_denref(y),1);
#endif
for(int i=0;i<10;++i){
#ifdef SLOW
b=mpq_cmp(x,y);
#else
mpq_sub(z,x,y);
b=mpq_sgn(z);
#endif
}
mpq_clear(z);
mpq_clear(y);
mpq_clear(x);
return 0;
}
--
Marc Glisse
More information about the gmp-discuss
mailing list