朱莉娅:@time一套功能

时间:2016-02-28 13:22:44

标签: time julia

我有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 个答案:

答案 0 :(得分:8)

注意:我想这只是一个示例,但语法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块方法。

答案 1 :(得分:4)

获得时间的一种方法是使用函数tic()toc()

示例:

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