You need to enable JavaScript to run this app. Julia时间测量与函数调用行为问题:TimerOutputs.jl异常现象求解
优惠活动
大模型
产品
解决方案
定价
更多

Julia时间测量与函数调用行为问题:TimerOutputs.jl异常现象求解

Q1 耗时差异原因

你观测到的上百倍耗时差完全来自Julia的JIT即时编译开销:

  • Julia首次执行自定义函数f时,会先将函数的中间代码编译为机器码,这部分编译动作是在你执行@timeit to "whole out" f()时触发的,编译全程的耗时、内存分配都会被计入whole out段的统计结果。
  • 而f内部的@timeit to "whole in"块,仅统计你显式包裹的代码段运行耗时,f本身的编译开销不会被计入内部任何计时块。你看到的310μs是完全排除编译开销的纯运行耗时,102ms的whole out时间是「f编译时间 + 纯运行时间」的总和,因此出现数量级差异。
    你可以直接验证该结论:首次运行完成后,再次执行@timeit to "whole out test" f(),此时f已经编译完成,你会看到whole out test的耗时和whole in的耗时基本一致,不会再出现百倍差距。

Q2 测量f总耗时、在f内部使用计时结果的实现方案

方案1:仅需准确测量f的总运行耗时

提前触发函数编译,排除JIT开销即可,操作如下:

# 先运行一次f完成预编译,不统计耗时
f()
# 清空此前的无效计时数据
reset_timer!(to)
# 此时计时结果为纯运行耗时,无编译开销
@timeit to "whole out" f()
show(to)

如果不需要外层计时,也可以直接把f的全部代码包裹在内部的计时块中,避免额外统计误差,还能直接在f内部拿到总耗时:

f = function()
    @timeit to "f总耗时" begin
        a = [];
        @timeit to "i section" begin
            for i in 1:1000
                push!(a,randn(5,5))
            end
        end
        @timeit to "x section" begin
            for x in 1:1000
                push!(a,randn(5,5) .+ x )
            end
        end
        # 这里直接读取总耗时,单位为纳秒
        total_runtime = TimerOutputs.time(to["f总耗时"])
        println("f当前总运行耗时:", total_runtime/1e6, "ms")
    end
end

方案2:需要在f内部获取外层whole out段的计时结果

whole out的计时从调用f前开始、到f完全返回后结束,因此在f执行过程中只能拿到当前已运行的实时时长,无法拿到最终总时长,读取方式如下:

f = function()
    # 你的业务逻辑
    # 运行过程中读取外层whole out的已运行时长,单位为纳秒
    current_total = TimerOutputs.time(to["whole out"])
    # 业务逻辑使用该时长
end

内容的提问来源于stack exchange,提问作者ten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 07:12:04