Redirect `@time` output into a string

Hello! working in a for loop I want to time a long computation with @time and I want to output the stdout into a string (that i’m using later in the for loop).

for _ in 1:num_loops
    @time myvar = longcomputation()
end

I want to keep the @time output inside a string variable and I also want to keep myvar as it get used later. How can I achieve this?



longcomputation() = (v = rand(); sleep(1e-5*rand()); v)

function run_loop(num_loops)
    times = []
    vals = Float64[]
    for _ in 1:num_loops
        t = @timed myvar = longcomputation()
        push!(times, t)
        push!(vals, myvar)
    end
    return times, vals
end

times, vals = run_loop(1000)

maybe. It won’t give you the exact @time output but it will have the data.

If you want to dig into some internals you can convert it to a string via:

function timed_to_str(ret)
    sprint() do io
        Base.time_print(io, ret.time*1e9, ret.gcstats.allocd, ret.gcstats.total_time, Base.gc_alloc_count(ret.gcstats), ret.lock_conflicts, ret.compile_time*1e9, ret.recompile_time*1e9, true)
    end
end
julia> map(timed_to_str, times)
1000-element Vector{String}:
 "  0.002077 seconds (4 allocations: 112 bytes)\n"
 "  0.002110 seconds (4 allocations: 112 bytes)\n"
 "  0.002121 seconds (4 allocations: 112 bytes)\n"
 "  0.002097 seconds (4 allocations: 112 bytes)\n"
 "  0.002075 seconds (4 allocations: 112 bytes)\n"
 "  0.002095 seconds (4 allocations: 112 bytes)\n"
 "  0.002107 seconds (4 allocations: 112 bytes)\n"
 "  0.002098 seconds (4 allocations: 112 bytes)\n"
 "  0.002118 seconds (4 allocations: 112 bytes)\n"
 "  0.002105 seconds (4 allocations: 112 bytes)\n"

I found this by looking at what @edit @time 1+1 does.

2 Likes

Amazing! Thank you a lot, yes I tried to replicate from timed but I was not able to figure it out.