Meta programming on fuction definning

There is a function:

function fun(x)
    a = x + 1
    b = x + 2
    return a + b
end

Is there a way I can do this?

@custom_macro function fun(x)
    a = x + 1
    b = x + 2
    return a + b
end

So the function fun is actually:

function fun(x)
    @time "line1" a = x + 1
    @time "line2" b = x + 2
    return a + b
end

Or is there a way I can do this?

function fun(x)
    a = x + 1
    b = x + 2
    return a + b
end

#when I run 
@custom_macro fun(10)
#It is actually running:
function fun(x)
    @time "line1" a = x + 1
    @time "line2" b = x + 2
    return a + b
end
1 Like

I’m not answering your question, but it looks like you want to get an idea of how different parts of an arbitrary function consume runtime. If that’s the case, check out profiling in Julia.

1 Like

I find a way:

macro time_each_line(x)
    args = x.args[2].args
    for i = 1 : size(args, 1)
        args[i] isa Expr || continue
        args[i] = :(@time $i $(args[i]))
    end
    quote 
        $x 
    end |> esc
end

But it is too messy. Any more elegant way ?