How do I get the memory size of a BigInt?

How do I get the memory size of a BigInt?
What I tried:

julia> x=big(3)^300
136891479058588375991326027382088315966463695625337436471480190078368997177499076593800206155688941388250484440597994042813512732765695774566001

julia> sizeof(x)
16

julia> Base.summarysize(x)
16

Thanks!

1 Like

There is

x=big(3)^300

@show Base.GMP.MPZ.sizeinbase(x,2)

yielding

Base.GMP.MPZ.sizeinbase(x, 2) = 476

but it doesn’t seem to be part of the public interface.

OK, this provides the number of digits in the given base.

I was more thinking about the actual amount of memory used. But I realize now that this is probably a bad question since Julia uses GMP for BigInts and GMP has its own nontrivial memory management and allocates memory outside the control of Julia.

So your answer provides a lower bound and, assuming that the overhead is not that big, a good estimator for the actual memory consumption.

Thank you,

I think you can get the allocated memory via the .alloc field, e.g.

julia> b = big(2)^512; (b.size, b.alloc)
(9, 13)

julia> 13 * Base.GMP.BITS_PER_LIMB / 8 # total number of allocated bytes
104.0
3 Likes

Also, what is documented is ndigits:

julia> ndigits(x, base=2)
476
2 Likes

Thank you!

j=big(17)^400;

for i = 1:10
    b=j^i
    limbs = b.size
    alloc = b.alloc
    minlimbs = ndigits(b, base=2) / Base.GMP.BITS_PER_LIMB 
    println("$alloc $limbs  $minlimbs")
end

gives

allocs #limbs ndigits/limbsize

52 52  51.09375
81 77  76.640625
107 103  102.1875
132 128  127.734375
158 154  153.28125
183 179  178.828125
209 205  204.375
234 230  229.921875
260 256  255.46875

so we have
b.size = #limbs = ceil( ndigits(b,2)/ limbsize) and
b.alloc = actually allocated memory (in units of limbsize)

I really think that summarysize should be taught about this so that it reports the memory used by BigInts accurately. Same deal with BigFloats too. Anyone want to file an issue or open a PR?

4 Likes

This is probably already fine for BigFloat as they store their data inline in a String field.

1 Like

https://github.com/JuliaLang/julia/issues/44780

1 Like