蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

JULIAJulia 1.10.13 官方便携版,Windows x64,本机隔离目录performance.jl
performance.jl147 行
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)
本例需在 Julia 1.10.13 官方便携版,Windows x64,本机隔离目录 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/julia-commands-performance/performance.jl

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 performance.jl,或下载右侧课程工程包。
  2. 确认本地已准备 Julia 1.10.13 官方便携版,Windows x64,本机隔离目录。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Julia

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a205.zip

下载课程关联工程包:Julia

课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a206.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习