Capturing the output of `@time` as a String

I would like to print the output of a @time in a production environment. To avoid cluttering up the logs, I try to keep a bit of discipline with the logging so everything should use a log level. Now my question is, how can I print @time with a info log-level? The following doesn’t work:

julia> @info @time sum([1, 2])
  0.000001 seconds (1 allocation: 80 bytes)
[ Info: 3

because @time prints to stdout. At the same time, capture_stdout requires me to write to a file (Redirect output to an IOBuffer · Issue #12711 · JuliaLang/julia · GitHub)?

EDIT: There is IOCapture.jl. It is a bit unfortunate to be required to install that. Maybe there is another workaround for this case.

Does @timed give you what you want? This returns the output of @time rather than printing to stdout.

julia> stats = @timed rand(10^6);

julia> stats.time
0.006634834
5 Likes

Perhaps you can just use @elapsed which, rather than returning the proper return value of the expression, returns the time elapsed to the call.
As far as I can tell it’s essentially @timed but only returns the time variable of the returned object i.e.

a = @elapsed f(x)
b = @timed f(x)
b.time == a # once both have been compiled
1 Like