循环时间测试

怎么利用@benchmark中的@belapsed测试循环中每一次循环所需要的时间,并把时间放到一个数组中
利用如下示例代码会出现,y没有被定义的错误
代码如下:

function foo()
    x=rand(10)
    y=0
  t=zeros(10)
 for i=1:10
    t[i]=@belapsed begin
        y=y+x[i]
    end
end
return y,t
end

y,t=foo()
 

错误提示如下:
y,t=foo()
ERROR: UndefVarError: y not defined
Stacktrace:
[1] macro expansion at .\REPL[56]:6 [inlined]
[2] ##core#264() at C:\Users\你好.julia\packages\BenchmarkTools\ms0Xc\src\execution.jl:479
[3] ##sample#265(::BenchmarkTools.Parameters) at C:\Users\你好.julia\packages\BenchmarkTools\ms0Xc\src\execution.jl:485
[4] _run(::BenchmarkTools.Benchmark, ::BenchmarkTools.Parameters; verbose::Bool, pad::String, kwargs::Base.Iterators.Pairs{Symbol,Integer,NTuple{4,Symbol},NamedTuple{(:samples, :evals, :gctrial, :gcsample),Tuple{Int64,Int64,Bool,Bool}}}) at C:\Users\你好.julia\packages\BenchmarkTools\ms0Xc\src\execution.jl:98
[5] (::Base.var"#inner#2"{Base.Iterators.Pairs{Symbol,Integer,NTuple{5,Symbol},NamedTuple{(:verbose, :samples, :evals, :gctrial, :gcsample),Tuple{Bool,Int64,Int64,Bool,Bool}}},typeof(BenchmarkTools._run),Tuple{BenchmarkTools.Benchmark,BenchmarkTools.Parameters}})() at .\essentials.jl:713
[6] #invokelatest#1 at .\essentials.jl:714 [inlined]
[7] #run_result#38 at C:\Users\你好.julia\packages\BenchmarkTools\ms0Xc\src\execution.jl:33 [inlined]
[8] run(::BenchmarkTools.Benchmark, ::BenchmarkTools.Parameters; progressid::Nothing, nleaves::Float64, ndone::Float64, kwargs::Base.Iterators.Pairs{Symbol,Integer,NTuple{5,Symbol},NamedTuple{(:verbose, :samples, :evals, :gctrial, :gcsample),Tuple{Bool,Int64,Int64,Bool,Bool}}}) at C:\Users\你好.julia\packages\BenchmarkTools\ms0Xc\src\execution.jl:116
[9] #warmup#47 at C:\Users\你好.julia\packages\BenchmarkTools\ms0Xc\src\execution.jl:168 [inlined]
[10] warmup(::BenchmarkTools.Benchmark) at C:\Users\你好.julia\packages\BenchmarkTools\ms0Xc\src\execution.jl:168
[11] macro expansion at C:\Users\你好.julia\packages\BenchmarkTools\ms0Xc\src\execution.jl:387 [inlined]
[12] foo() at .\REPL[56]:5
[13] top-level scope at REPL[57]:1

我觉得问题出在对于@belapsed的理解上面:

help?> @belapsed
  @belapsed expression [other parameters...]

  Similar to the @elapsed macro included with Julia, this returns the elapsed time (in seconds) to execute a given
  expression. It uses the @benchmark macro, however, and accepts all of the same additional parameters as @benchmark.
  The returned time is the minimum elapsed time measured during the benchmark.

加入一个函数跑10遍,那么@belapsed只会给出一个最快的时间,这和@elapsed是不一样的。

感谢您的答复,想问一下除了利用@elapsed, 有没有什么方法可以将循环中每一次循环的时间都记录下来,放到一个数组里面输出,测试的时间可以排除编译时间以及一些其他的噪音干扰。因为我在这里利用@belapsed测试是因为它可以排除编译的时间以及一些其他的噪音干扰。

我没有仔细研究过benchmarktools.jl这个包,所以类似你想要的功能可能还需要翻看它的手册。不过呢,从宏观层面上,@btime这一系列的macro主要做的事情是通过反复运行同一个函数来减少噪音,并忽略首次运行时间来剔除编译时间。所以如果只是一些简单的测试,多运行几遍的测量时间和btime并不会有什么本质区别。

好的非常感谢,我再看一看