简体   繁体   English

Julia 中的 For Loop 每次迭代的时间?

[英]Time each iterations of For Loop in Julia?

Given a for loop , is there some macro/function that times each iteration of the loop, and returns this info as a tuple or array (or similar)?给定一个for 循环,是否有一些宏/函数对循环的每次迭代进行计时,并将此信息作为元组或数组(或类似)返回? Would there be any way to assign such tuple or array to a variable (for example, I am not sure how to assign output of @time macro to a variable).有没有办法将这样的元组或数组分配给变量(例如,我不确定如何将@time 宏的 output 分配给变量)。 I am aware of the @timed macro, but not sure how to extract the tuple that @timed gives/assign to variable.我知道@timed宏,但不确定如何提取@timed 提供/分配给变量的元组。 Below is an example of a for loop where each iteration might be timed?下面是一个 for 循环的示例,其中每次迭代都可能是定时的?

 for x=1:10
     println("$x is my number.") 
 end

Like this?像这样?

function timeloop(n)
    tvec = zeros(n)
    for x = 1:n
        t = @elapsed println("$x is my number.")
        tvec[x] = t
    end
    tvec
end

timeloop(9)
1 is my number.
2 is my number.
3 is my number.
4 is my number.
5 is my number.
6 is my number.
7 is my number.
8 is my number.
9 is my number.

9-element Vector{Float64}:
 0.0002649
 0.0001195
 0.0001018
 9.44e-5
 8.25e-5
 6.8e-5
 8.52e-5
 7.39e-5
 8.5e-5

As per Julia help, @elapsed is a macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.根据 Julia 帮助, @elapsed是一个用于评估表达式的宏,丢弃结果值,而是将执行所需的秒数作为浮点数返回。

For timing multi-line expressions/statements, use the t = @elapsed begin.. end form.对于计时多行表达式/语句,请使用t = @elapsed begin.. end形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM