性能分析 #

一、基本计时 #

1.1 @time #

julia
@time sum(rand(10^6))

1.2 @timed #

julia
result = @timed sum(rand(10^6))
result.time
result.bytes
result.value

1.3 @elapsed #

julia
@elapsed sum(rand(10^6))

1.4 @allocated #

julia
@allocated sum(rand(10^6))

二、Profile模块 #

2.1 基本使用 #

julia
using Profile

function slow_function(n)
    total = 0.0
    for i in 1:n
        total += sqrt(i)
    end
    return total
end

@profile slow_function(10^6)
Profile.print()

2.2 清除配置文件 #

julia
Profile.clear()

2.3 配置采样 #

julia
Profile.init(n=10^6, delay=0.001)

2.4 ProfileViz #

julia
using Pkg
Pkg.add("ProfileViz")

using ProfileViz

@profview slow_function(10^6)

三、内存分析 #

3.1 @allocated #

julia
function allocate_test()
    x = [1, 2, 3, 4, 5]
    sum(x)
end

@allocated allocate_test()

3.2 @time内存信息 #

julia
@time allocate_test()

3.3 MemoryProfiler #

julia
using Pkg
Pkg.add("MemoryProfiler")

using MemoryProfiler

@profile_memory allocate_test()

四、类型分析 #

4.1 @code_warntype #

julia
function unstable(x)
    if x > 0
        return x
    else
        return "negative"
    end
end

@code_warntype unstable(1)

4.2 @code_typed #

julia
@code_typed unstable(1)

4.3 @code_llvm #

julia
@code_llvm unstable(1)

4.4 @code_native #

julia
@code_native unstable(1)

五、JET分析器 #

5.1 安装 #

julia
using Pkg
Pkg.add("JET")

5.2 基本使用 #

julia
using JET

@report_opt unstable(1)

5.3 类型错误检测 #

julia
using JET

function buggy(x)
    if x > 0
        return x
    else
        return "error"
    end
end

@report_call buggy(1)

六、实践练习 #

6.1 练习1:性能分析 #

julia
using Profile

function fibonacci(n)
    n <= 1 ? n : fibonacci(n-1) + fibonacci(n-2)
end

@profile fibonacci(30)
Profile.print()

6.2 练习2:内存优化 #

julia
function bad_sum(arr)
    total = 0
    for x in arr
        total += x
    end
    return total
end

function good_sum(arr)
    total = 0.0
    for x in arr
        total += x
    end
    return total
end

arr = rand(10^6)
@time bad_sum(arr)
@time good_sum(arr)

6.3 练习3:类型稳定性检查 #

julia
function check_type_stability(f, args...)
    code = @code_warntype f(args...)
    if occursin("Any", string(code))
        @warn "Type instability detected"
        return false
    end
    return true
end

check_type_stability(x -> x > 0 ? x : 0.0, 1)

七、总结 #

本章我们学习了:

  1. 基本计时:@time、@timed、@elapsed
  2. Profile模块:性能采样和分析
  3. 内存分析:@allocated和内存分析器
  4. 类型分析:@code_warntype等
  5. JET分析器:静态分析工具

接下来让我们学习Julia的优化技巧!

最后更新:2026-03-27