蓝色天空网mbsky.com · 知识 · 实践 · 创造Julia · 本地阅读预览
教程 / Python / 数据科学 / Julia

Julia 性能测量与优化

对比函数入口、类型推断、内存分配、遍历顺序、视图和广播融合。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先区分启动开销和重复运行

先定义能独立调用的计算函数,使用相同输入验证结果,然后用 @time 观察时间和分配,或用 @timed 取得结构化数据。首次调用可能含编译,先执行一次再采样可缩小差异。正式比较需多次采样,BenchmarkTools 的 @btime 可做重复测量。它使用全局输入时通常应做插值。

可替换的全局值会限制推断。通常把输入作为参数传入热点函数。const 固定绑定而不冻结绑定的向量。练习先验证参数、全局和常量三个入口都算出 500500;分配和耗时以本次环境输出为准。

读懂类型报告

同一 Float64 参数签名下,直接返回整数 0 或原值会得两种返回类型,zero(x) 可让这两个分支都返回 Float64。循环累加器从 8 开始做除法会变为 Float64,8.0 起步可保持一致。用 @code_warntype 或 code_warntype(io, fn, ...) 查明推断结果。小联合类型可由编译器优化,需结合测量判断影响。

Real 元素和 AbstractFloat 字段表达允许多种实际类型。对于同质数据,用 Float64 数组和参数化字段可给出更具体的类型信息。保存可调用对象也可用结构体类型参数,能容纳可调用结构体并保留类型,具体优化效果取决于调用位置。

分配、顺序和别名

预分配输出可让循环复用同一块内存。比较时应检查结果和输出对象身份。练习使用 8192 个值,分别观察新数组和复用数组的分配。

密集 Matrix 的第一维连续。128 行矩阵的 stride 是 (1, 128),优先沿第一维遍历,可按相邻内存位置读写。行内与列内循环必须先确认复制相同的数据。耗时还受尺寸、缓存与运行时影响。

范围切片通常生成独立副本,view 或 @views 创建借用原数组的视图。实验修改视图会改变原数组,而修改副本保持原数组对应位置。非连续视图反复使用时,复制到连续数组也可能更合适。

多个连续点运算可融合为一个广播。@. 作用于整个标注表达式,必须确认需要逐元素处理的调用。fused_into! 通过点赋值复用输出,而分配版返回新数组。练习核对近似相等和实际分配变化。

尺寸特化和编译延迟

固定且很小的数组可评估 StaticArrays 的 SVector。它把长度纳入类型,能带来尺寸特化,分配位置和性能仍由具体程序决定。本站使用固定二元组算出长度 13,独立展示固定长度输入。

首次加载和首次调用要分别测量。PrecompileTools 可为常见负载建立预编译结果,PackageCompiler 可生成自定义系统镜像。可在新进程逐个测 using 或 import,查找不必要的依赖,保留运行确实需要的包。

加载和首次执行延迟

办法适用条件
PrecompileTools.jl用典型工作负载触发可缓存的预编译,减轻用户首次调用的延迟。
PackageCompiler.jl用定制系统镜像预装包与编译结果,并管理镜像绑定的版本。
减少依赖在新的 Julia 进程中量 import 或 using 成本,移除实际用不到的依赖。

性能检查

检查项做法
代码在函数里吗?把热点放在函数里并显式传入数据,从可以重复调用的入口测量。
有全局变量吗?传入输入参数,稳定的全局绑定可用 const;这并不冻结所指容器。
类型稳定吗?用 code_warntype 观察推断,明确返回类型随值变化是否出现在热点。
容器类型具体吗?同质数值容器可选用具体元素类型,持有抽象接口的字段也可参数化。
分配多吗?对可复用输出考虑原地写入,先确认输出值、生命周期与别名约束。
循环顺序对吗?对普通密集 Matrix,让第一维在内层变化通常能提高访问局部性。
该用点语法吗?同形逐元素表达式可用点运算融合;可用 .= 复用输出。
数组小而固定吗?可比较固定尺寸工具,如 StaticArrays;本站元组只说明固定长度的输入。
切片要复制吗?独立数据需要复制,临时借用可用 view 或 @views 并留意别名。

实测输出复用、数组步幅与分配

julia · 阅读源码
using InteractiveUtils
include(joinpath(@__DIR__, "observations.jl"))

function measured(name,input,actual,valid,contract)
    valid || error(name,": ",repr(actual))
    println(join((name,repr(input),repr(contract),repr(actual)),'\t'))
end

samples = collect(1:1000)
const FIXED_SAMPLES = collect(1:1000)
sum_argument(data) = sum(data)
sum_global() = sum(samples)
sum_const() = sum(FIXED_SAMPLES)

function local_loop(n)
    total = 0
    for i in 1:n
        total += i
    end
    return total
end

function timed(action)
    action()
    return @timed action()
end

top = 0
for i in 1:1000
    global top += i
end
probe("perf_function", 1000, (top,local_loop(1000)),(500500,500500))
probe("perf_globals", "same integer vector", (sum_argument(samples),sum_global(),sum_const()),(500500,500500,500500))
probe("perf_const","constant binding type",isconst(Main,:FIXED_SAMPLES),true)
report = timed(() -> sum_argument(samples))
observed = (value=report.value,elapsed_seconds=report.time,allocated_bytes=report.bytes)
measured("perf_timing", "1000 integers after one warmup",observed,
         report.value==500500 && report.time>=0 && report.bytes>=0,
         "sum is 500500, time and allocation measurements nonnegative")

clamp_mixed(x) = x < 0 ? 0 : x
clamp_stable(x) = x < 0 ? zero(x) : x
probe("perf_return", (-1.5,2.5), map(typeof,(clamp_mixed(-1.5),clamp_mixed(2.5),
                                          clamp_stable(-1.5),clamp_stable(2.5))),
      (Int,Float64,Float64,Float64))
function scale_steps(initial)
    x=initial
    types=DataType[typeof(x)]
    for _ in 1:3
        x /= 2
        push!(types,typeof(x))
    end
    return x,types
end
probe("perf_loop_type", (8,8.0), (scale_steps(8),scale_steps(8.0)),
      ((1.0,[Int,Float64,Float64,Float64]),(1.0,fill(Float64,4))))
function type_report(fn)
    io=IOBuffer()
    code_warntype(io,fn,Tuple{Float64})
    return String(take!(io))
end
mixed,stable = type_report(clamp_mixed),type_report(clamp_stable)
probe("perf_warntype", "Float64 inference reports",
      (occursin(r"body::union\{(float64, int64|int64, float64)\}",lowercase(mixed)),occursin("Body::Float64",stable)),(true,true))
abstract_elements = Real[2,4.5,8]
float_elements = Float64[2,4.5,8]
probe("perf_elements","same numbers with abstract and concrete eltype",
      (eltype(abstract_elements),eltype(float_elements),sum(abstract_elements),sum(float_elements)),
      (Real,Float64,14.5,14.5))
struct AbstractGauge
    value::AbstractFloat
end
struct TypedGauge{T<:AbstractFloat}
    value::T
end
probe("perf_field",2.5,(fieldtype(AbstractGauge,1),fieldtype(typeof(TypedGauge(2.5)),1),TypedGauge(2.5).value),
      (AbstractFloat,Float64,2.5))
struct AbstractTransform
    f::Function
end
struct TypedTransform{F}
    f::F
end
amplify(x)=3x
a,b=AbstractTransform(amplify),TypedTransform(amplify)
probe("perf_callable",4,(fieldtype(typeof(a),1),fieldtype(typeof(b),1),a.f(4),b.f(4)),
      (Function,typeof(amplify),12,12))

fresh(data) = [value+1 for value in data]
function refill!(target,data)
    for i in eachindex(data,target)
        target[i]=data[i]+1
    end
    return target
end
values = collect(1.0:8192.0)
output = similar(values)
new_out = timed(() -> fresh(values))
reused = timed(() -> refill!(output,values))
measured("perf_preallocation", length(values),(fresh_bytes=new_out.bytes,reused_bytes=reused.bytes),
         new_out.value==reused.value && reused.value===output && new_out.bytes>reused.bytes,
         "equal values, output identity preserved, reused allocation smaller")

function copy_order(a, first_dimension_inner)
    out=similar(a)
    if first_dimension_inner
        for j in axes(a,2), i in axes(a,1)
            out[i,j]=a[i,j]
        end
    else
        for i in axes(a,1), j in axes(a,2)
            out[i,j]=a[i,j]
        end
    end
    return out
end
matrix = reshape(collect(1:8192),128,64)
column = timed(() -> copy_order(matrix,true))
row = timed(() -> copy_order(matrix,false))
measured("perf_order",size(matrix),(strides=strides(matrix),column_seconds=column.time,row_seconds=row.time),
         strides(matrix)==(1,128) && column.value==row.value==matrix,
         "both copies match, first dimension has stride one")

function view_alias()
    original=[4,5,6,7]
    copied=original[2:3]
    borrowed=@view original[2:3]
    copied[1]=20
    borrowed[2]=60
    return original,copied,collect(borrowed)
end
probe("perf_view_alias", (2:3,20,60), view_alias(), ([4,5,60,7],[20,6],[5,60]))
copy_sum(data) = sum(data[2:end-1])
view_sum(data) = @views sum(data[2:end-1])
copied,borrowed=timed(() -> copy_sum(values)),timed(() -> view_sum(values))
measured("perf_view",length(values),(copy_bytes=copied.bytes,view_bytes=borrowed.bytes),
         copied.value==borrowed.value && copied.bytes>borrowed.bytes,"equal sums, view allocation smaller")

unfused(x)=3*x.^2 + 4*x + 7*x.^3
fused(x)=@. 3*x^2 + 4*x + 7*x^3
fused_into!(out,x)=(@. out = 3*x^2 + 4*x + 7*x^3)
slow,fast,into=timed(() -> unfused(values)),timed(() -> fused(values)),timed(() -> fused_into!(output,values))
measured("perf_broadcast",length(values),(unfused_bytes=slow.bytes,fused_bytes=fast.bytes,into_bytes=into.bytes),
         slow.value≈fast.value && fast.value≈into.value && into.value===output && slow.bytes>fast.bytes>into.bytes,
         "equal values, fused allocates less, in-place writes existing output")
probe("perf_tuple",(5.0,12.0),hypot((5.0,12.0)...),13.0)
预期结果 · 待实际运行核验
  • 两种遍历复制相同矩阵,第一维步幅为 1。视图和复制的和相同,视图修改可见于原数组。本次热身后的测量中,输出复用、视图与点融合分别减少对应的分配。
实测输出复用、数组步幅与分配

所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录

当前源码 SHA256:30ee8091227d54823932f5c31c01833bc4314d15946581c12dbcf93d4b851e7f

下载本站示例源码

解压练习

按 README 分别运行外部命令和性能实验。

下载本站 Julia 外部命令与性能练习

所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录

ZIP SHA256:ac456c027e2762f468d7f9480cf68dd082e6c4df2c1ed1a3714eef14a8e11aa9

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

怎样避免把首次编译计入重复计算的采样?

展开参考解答

先调用相同签名预热,保持输入条件相同,再重复采样并记录分配和输出。

规范与官方依据