Why does rand() report no allocations, but zeros() does when measured with --track-allocation=user?

Very basic question: I’m trying to understand why the instantiation of A in the following small example doesn’t appear to produce any allocations in the profiling output:

        - function testfunc()
        0     A = rand(1001,2,3);
        -
    48144     B = zeros(1001,2,3);
        - end

However, if I change the instantiation of A to use zeros instead of rand I get:

        - function testfunc()
    48144     A = zeros(1001,2,3);
        -
    48144     B = zeros(1001,2,3);
        - end

which makes more sense to me.

What is the origin of the difference in these two outputs?

To be clear, I got these results with julia --track-allocation=user and ran

julia> testfunc();

julia> Profile.clear_malloc_data()

julia> testfunc();

to generate these results.

Update Just to add, although the runtimes unsurprisingly differ, both examples report the (identical) expected size of allocation when measured with @btime:

julia> @btime testfunc();
  6.637 μs (4 allocations: 94.03 KiB)

So I’m curious how I can get the output of @btime to be assigned to the “responsible” lines in my code.

Just a guess,

but I would expect the memory for rand to be allocated inside rand function and the assignment A = rand(...) is just a binding of a name. If you dive to rand, you should see the allocation.

Interesting; so is there a way to record cumulative allocations? I’d like both lines to show that, as they are run, they both allocate the same amount of memory, to help me understand where allocations are being generated within my own code.

I have no idea, but for measure time and allocations in your code I recommend to use TimerOutputs.jl it is very simple and useful.

1 Like