:@allocated
@allocated
A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression. Note: the expression is evaluated inside a local function, instead of the current context, in order to eliminate the effects of compilation, however, there still may be some allocations due to JIT compilation. This also makes the results inconsistent with the @time
macros, which do not try to adjust for the effects of compilation.
Examples
In the Julia programming language, the @allocated
macro is used to evaluate an expression and return the total number of bytes allocated during the evaluation. It is important to note that the expression is evaluated inside a local function to eliminate the effects of compilation, but there may still be some allocations due to JIT compilation. The results obtained from @allocated
may be inconsistent with the @time
macros, which do not attempt to adjust for the effects of compilation.
Here are some examples of how @allocated
can be used:
-
Measure memory allocation of a simple expression:
julia> @allocated a = 2 + 3 0
In this example,
@allocated
is used to measure the memory allocation when evaluating the expression2 + 3
. Since this is a simple expression without any memory allocations, the result is 0. -
Measure memory allocation of a function call:
julia> function foo(n) return [i for i in 1:n] end julia> @allocated foo(1000) 8000
Here,
@allocated
is used to measure the memory allocation of the function callfoo(1000)
. It returns the total number of bytes allocated during the evaluation of the function. -
Compare memory allocations between expressions:
julia> @allocated a = rand(1000, 1000) 8000112 julia> @allocated b = zeros(1000, 1000) 0
This example demonstrates how
@allocated
can be used to compare memory allocations between different expressions. In this case, it measures the memory allocation of generating a random matrix (rand(1000, 1000)
) and creating a zero-filled matrix (zeros(1000, 1000)
).
It's important to note that the values obtained from @allocated
may vary depending on the system, Julia version, and other factors. The purpose of @allocated
is to provide a measure of memory allocation rather than an absolute value.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.