Best way to know how much memory is used by an mpz_class object

Torbjorn Granlund tege at
Mon Dec 6 16:46:28 CET 2004

Roberto Bagnara <bagnara at> writes:

  In my application I need a way to compute the amount of memory
  that is used by an object of type `mpz_class'.
  What I do now is something like
     sizeof(x) + x.get_mpz_t()[0]._mp_alloc*SIZEOF_MP_LIMB_T
  which, however, relies on the low-level implementation of
  Is there a more portable or better way to achieve the same effect?

There is no way to directly determine the amount of memory used,
as far as I can tell.  It might be adequate to use
mpz_realloc2(x,mpz_sizeinbits(x,2)) to set GMP's idea of
allocation manually.

Note, however, that the used amount is often up to about twice
what has been asked for, since most malloc implementations pad
out to certain fixed sizes.


More information about the gmp-discuss mailing list