..  @code_native

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


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

julia> function foo(x)
           return x * 2
foo (generic function with 1 method)

julia> @code_native foo(5)
; ┌ @ REPL[1]:2 within `foo'
        pushq   %rbp
        movq    %rsp, %rbp
        leaq    (%rdi,%rdi), %rax
        popq    %rbp
        nopw    %cs:(%rax,%rax)
; └

The @code_native macro is used to generate the native assembly code for the given function call. Here are some common examples of its use:

  1. Inspect the assembly code for a function:

    julia> @code_native sin(1.0)
    ; ┌ @ float.jl:326 within `sin'
        pushq   %rbp
        movq    %rsp, %rbp
        movsd   (%rdi), %xmm0
        callq   0x1370                 ; symbol sin
        popq    %rbp
        nopw    %cs:(%rax,%rax)
    ; └

    This example shows the assembly code for the sin function when called with a Float64 argument.

  2. Analyze the performance of a specific function call:
    julia> @code_native sum([1, 2, 3, 4, 5])
    ; ┌ @ reduce.jl:804 within `sum'
        pushq   %rbp
        movq    %rsp, %rbp
        xorps   %xmm0, %xmm0
        testq   %rdi, %rdi
        je      L103
        nopw    %cs:(%rax,%rax)
    ; │┌ @ reduce.jl:804 within `sum'
    ; ││┌ @ reduce.jl:806 within `sum'
    ; │││┌ @ reduce.jl:805 within `sum'
    ; ││││┌ @ reduce.jl:805 within `sum'
    ; │││││┌ @ reduce.jl:806 within `sum'
    ; ││││││┌ @ reduce.jl:807 within `sum'
    ; │││││││┌ @ reduce.jl:804 within `sum'
        xorps   %xmm1, %xmm1
    ; │││└└└└└
    ; │││ @ reduce.jl:808 within `sum'
        movq    (%rdi), %rax
        addq    $8, %rdi
        addsd   (%rax), %xmm0
        cmpq    %rax, %rdi
        jne     -0x10                    ; ││ @ reduce.jl:808 within `sum'
        jmp     L102                     ; │└
    ; │└
    L103:                                   ; │ @ reduce.jl:804 within `sum'
        movsd   %xmm1, (%rsp)
    L102:                                   ; │ @ reduce.jl:804 within `sum'
        movsd   (%rsp), %xmm1
        popq    %rbp
        nopw    (%rax,%rax)
    ; └

    Here, the assembly code for the sum function when called with an array is shown.

Common mistake example:

julia> @code_native "hello"
ERROR: @code_native: argument must be a symbol or expression, not a string

In this example, a common mistake is passing a string literal as an argument to @code_native. Instead, the argument should be a symbol or an expression that can be evaluated.

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

Checking you are not a robot: