朱莉娅:@time 一组函数

6

我有一个名为script.jl的脚本,大致上看起来像这样:

...

function main()
    a::... = function1()
    b::... = function2(...)
    c::... = function3(...)
    A::... = function4(...)
    B::... = function5(...)
    C::... = function6(...)
end

main()

我无法计算 @time main(),因为1-3函数是输入函数,所以它们的执行时间取决于用户的快慢。 有没有办法只计算4-6函数的时间? 我不知道,可以尝试这样做:

...

function main()
    a::... = function1()
    b::... = function2(...)
    c::... = function3(...)
    @time(
    A::... = function4(...)
    B::... = function5(...)
    C::... = function6(...)
    )
end

main()
2个回答

12

注意:我猜这只是一个例子,但语法C::...不是有效的Julia语法,最好提供简单而功能性的示例。

如果您想要独立计时,可以使用@time宏注释在每个您感兴趣的表达式之前:

function main()
    a = function1()
    b = function2(...)
    c = function3(...)
    @time A = function4(...)
    @time B = function5(...)
    @time C = function6(...)
end

main()
或:
function main()
    a = function1()
    b = function2(...)
    c = function3(...)
    @time begin
        A = function4(...)
        B = function5(...)
        C = function6(...)
    end
end

main()

这类似于@Gomiero的答案,只是为了使用@time宏来计时多个函数,您需要引入一个新的代码块并将所有内容放在其中。

还要检查尚未注册的包Benchmarks,例如:

julia> Pkg.add("https://github.com/johnmyleswhite/Benchmarks.jl.git")

julia> using Benchmarks

julia> function test()
           x = 0
           for i in 1:1000_000_000
               x += 1
           end
           return x
       end
test (generic function with 1 method)

julia> @time test()    # JIT warmup!
  0.003669 seconds (1.71 k allocations: 90.799 KB)
1000000000

julia> @time test()
  0.000002 seconds (5 allocations: 176 bytes)
1000000000

julia> @benchmark test()
================ Benchmark Results ========================
     Time per evaluation: 6.03 ns [5.92 ns, 6.13 ns]
Proportion of time in GC: 0.00% [0.00%, 0.00%]
        Memory allocated: 0.00 bytes
   Number of allocations: 0 allocations
       Number of samples: 6301
   Number of evaluations: 811601
         R² of OLS model: 0.951
 Time spent benchmarking: 2.96 s

如果您想计时多个表达式,请使用begin块方法。


将结果保存到一个变量中怎么样(仅运行时结果)? - Royi
@Royi 那么你只需要执行 x = @time foo() 或者 x = @btime foo(),其中 @btime 是来自于 BenchmarkTools 库的。 - HarmonicaMuse
1
实际上,@btime 会将函数结果放入变量中。如果有人(如上面所述的 A)想要将运行时间设置为一个变量,则应该使用 runTime = @elapsed foo();runTime = @belapsed foo();,前提是使用了 BenchmarkTools.jl - Royi
1
@Royi 哦,明白了,我之前没有理解你的意思,很高兴你找到了解决方法。 - HarmonicaMuse

4

获取经过的时间的一种方法是使用tic()和toc()函数:

示例:

function main()
    a::... = function1()
    b::... = function2(...)
    c::... = function3(...)
    tic()
    A::... = function4(...)
    B::... = function5(...)
    C::... = function6(...)
    toc()
end

更新:Julia版本>=1.0中的tic和toc函数已被弃用,不再可用。你可以使用@time如@SalchiPapa的答案所述或使用包BenchmarkTools.jl,该包具有许多用于跟踪Julia代码性能的出色功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接