Check byte size of variable with Julia

Question: How to check the byte size of a variable using Julia?

What I tried: In Matlab, the function whos()provided this information, but in Julia, which simply provides the variable names and the module. Looking at the standard library in the Julia manual sizeof()looked promising, but apparently it provides the size of the canonical binary representation, not the current variable.

+5
source share
2 answers

sizeof also works with variables

SizeOf (a :: array {T, N})

returns the size of the array times the size of the element.

julia> x = [1 2 3 4]
1x4 Array{Int64,2}:
 1  2  3  4

julia> sizeof(x)
32

julia> x = Int8[1 2 3 4]
1x4 Array{Int8,2}:
 1  2  3  4

julia> sizeof(x)
4

SizeOf (B :: BitArray {N})

; 8 , 64

julia> x = BitArray(36);
julia> sizeof(x)
8 

julia> x = BitArray(65);
julia> sizeof(x)
16

sizeof (s :: ASCIIString) sizeof (s :: UTF8String)

(1 /).

julia> sizeof("hello world")
11

sizeof (s :: UTF16String) sizeof (s :: UTF32String)

, , 2 4 .

julia> x = utf32("abcd");
julia> sizeof(x)
16

sizeof(s::SubString{ASCIIString}) at string.jl:590
sizeof(s::SubString{UTF8String}) at string.jl:591
sizeof(s::RepString) at string.jl:690
sizeof(s::RevString{T<:AbstractString}) at string.jl:737
sizeof(s::RopeString) at string.jl:802
sizeof(s::AbstractString) at string.jl:71

,

julia> x = Int64(0);
julia> sizeof(x)
8

julia> x = Int8(0);
julia> sizeof(x)
1

julia> x = Float16(0);
julia> sizeof(x)
2

julia> x = sizeof(Float64)
8

, , -

julia> sizeof('a')
4

GetBytes

, / . , ( ) sizeof, .

getBytes(x::DataType) = sizeof(x);

function getBytes(x)
   total = 0;
   fieldNames = fieldnames(typeof(x));
   if fieldNames == []
      return sizeof(x);
   else
     for fieldName in fieldNames
        total += getBytes(getfield(x,fieldName));
     end
     return total;
   end
end

random-ish...

julia> type X a::Vector{Int64}; b::Date end

julia> x = X([i for i = 1:50],now())
X([1,2,3,4,5,6,7,8,9,10  …  41,42,43,44,45,46,47,48,49,50],2015-02-09)

julia> getBytes(x)
408
+10

Base.summarysize

, .

julia> struct Foo a; b end

julia> Base.summarysize(ones(10000))
80040

julia> Base.summarysize(Foo(ones(10000), 1))
80064

julia> Base.summarysize(Foo(ones(10000), Foo(ones(10, 10), 1)))
80920

, .

+1

All Articles