I found that the @debug macro has a massive performance impact on my code. I use the macro very often, because the documentation says:
[The macro] will produce no output by default. Furthermore, it’s very cheap to leave debug statements like this in the source code because the system avoids evaluating the message if it would later be ignored.
But it looks like this is not cheap, see the MWE, that is 10x slower by placing the macro in a fast evaluating function from the documentation examples.
Am I doing something wrong? Otherwise there should be a note in the docu that the macro should not be used in (performance) optimized code.
Thank you & best regards!
MWE (Julia 1.9.2)
using BenchmarkTools
function my_sum(x)
return sum(x)
end
function my_sum_debug(x)
@debug "The given x is " x
return sum(x)
end
x = rand(1000)
@btime my_sum($x) # 61.702 ns (0 allocations: 0 bytes)
@btime my_sum_debug($x) # 755.752 ns (2 allocations: 112 bytes)
Well, it’s absolutely cheap, not relatively. There is some small but fixed overhead (use @macroexpand to see the expression generated by @debug), and because the workload in your example is trivial, it becomes very noticeable. Make x a hundred times larger, and the impact of the debug statement is “only” about 3% (on my machine).
Please also note that you should always interpolate external variables into benchmark expressions
@btime my_sum($x)
for an accurate measurement.
Edit: I concur with Mason below. The overhead in the original example is ~2x for me as well. 10x seems really excessive.
I see that the overhead for a single evaluation is not much, but in my special case it had a noticable effect, because there where thousands of @debug evaluations per second (which I thought were totally ignored as long as debugging is disabled) - I basically used it for easy print-debugging a entire software library.
Importantly, I’m not incurring any allocations from the debug statements, and they’re only taking ~60 extra nanoseconds rather than ~600 extra nanoseconds.
Are you sure you’re not in a mode where the debug statements are being saved to a file or something?
@mihalybaci@nilshg@ThummeTo do you see similar performance problems on earlier versions of julia? e.g. 1.6 or 1.0? I’m curious if this is something that’s always been this way or is a recent regression.
I also see the slowdown on v1.6.7, but @skleinbo 's trick of disabling logging pretty much eliminates it on the older and newer versions. There is a persistent ~20 ns difference (roughly 20%), but maybe that’s within the error?
I can confirm that Logging.disable_logging(Debug) solves this in Julia 1.6.7 as well as in 1.9.3, the timing difference almost vanishes and we have zero allocations: