Macro to print line number and time of execution (@time + line number)?

question

#1

@time prints useful information about the time it took to evaluate a command. Is there a way to also print on the same line the line number where @time is located in a source file?


#2

https://docs.julialang.org/en/latest/stdlib/file/#Base.@LINE


#3

Thanks. I knew that. I meant if there is a way to combine the output of @time with the line number, in a single printed line.


#4

by writing a macro that prints @__LINE__ and then runs @time?


#5

I don’t know how to write macros.


#6

This one should be a simple macro, something like

macro timeonline(expr)
    quote
        println("was executed on line $(@__LINE__)")
        @time $(esc(expr))
    end
end

#7

Thank you! Just one more thing. Is there a way to print both the time and line number on the same printed line? Something like:

line 123: 3.552151 seconds (4.32 M allocations: 185.869 MiB, 25.28% gc time)


#8

Have you tried print instead of println ?


#9

Yes, that works. Thanks.


#10

After some more testing, I realized that this is actually printing the line number of the macro, not the line number where the macro is called. Can we fix this?


#11

Sorry, I overlooked that. That is not very easy; the only trick I know it is here.


#12

__source__ on 0.7/master


#13

Where is it defined? Can I use it in 0.6?


#14

I don’t fully understand this, but can one force the @__LINE__ to expand at the call-site instead of within the macro?


#15

See also DebuggingUtilities.jl


#16

With help from the Gitter community, we came up with a workaround (back for v0.4) for our debugging and logging macros that has worked well (overhead of using backtrace would have been too large).
The first argument to our macros is an anonymous function, and by looking inside it (it’s never even compiled or executed), we are able to extract the line and file number for where the macro is called (we also pick out a status code from the anonymous function, for convenience sake)
For example:
@error(()->ERR_INVALID_INPUT, "logged error message")
I was hoping that v0.6 would have some way of directly getting the line number / file name directly in the macro, but this has done the job for us, and is not too ugly).