:@code_typed

..  @code_typed

Evaluates the arguments to the function call, determines their types, and calls :func:`code_typed` on the resulting expression.

Examples

The @code_typed macro in Julia evaluates the arguments to a function call, determines their types, and calls the code_typed function on the resulting expression.

julia> function add_numbers(x, y)
           return x + y
       end

julia> @code_typed add_numbers(3, 4)
CodeInfo(
    @ REPL[1]:2 within `add_numbers`
1 ─     return x + y
) => CodeInfo(
1 ─ %1 = (Base.add_int)(x, y)::Int64
└──      return %1
)

In this example, @code_typed is used to analyze the types of the arguments 3 and 4 passed to the add_numbers function. The resulting CodeInfo object shows the typed expression and the inferred types.

Common examples of using @code_typed:

  1. Inspecting a function call with multiple arguments:

    julia> @code_typed sin(1.5)
    CodeInfo(
    1 ─ %1 = invoke Main.sin(_2::Float64)::Float64
    └──      return %1
    )

    This example shows the typed expression for the sin function call with a single argument 1.5.

  2. Analyzing code within a function:

    julia> function my_function(x)
              y = x * 2
              return y
          end
    
    julia> @code_typed my_function(10)
    CodeInfo(
    1 ─ %1 = (Base.mul_int)(x, 2)::Int64
    └──      return %1
    )

    Here, the @code_typed macro is used to analyze the code within the my_function function and display the typed expression.

  3. Examining code involving custom types:

    julia> struct MyType
              value::Int64
          end
    
    julia> my_instance = MyType(42);
    
    julia> @code_typed my_instance.value
    CodeInfo(
    1 ─      return x.value
    )

    In this case, @code_typed is used to analyze the code accessing the value field of a custom MyType object.

Remember that @code_typed provides insights into the typed expression and the inferred types. It can be useful for understanding how Julia compiles and optimizes code.

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.

*Required Field
Details

Checking you are not a robot: