Skip to content

Instantly share code, notes, and snippets.

@JeffreySarnoff
Last active September 19, 2022 12:01
Show Gist options
  • Save JeffreySarnoff/d945d32d75eaa499d928576b8a3d7a87 to your computer and use it in GitHub Desktop.
Save JeffreySarnoff/d945d32d75eaa499d928576b8a3d7a87 to your computer and use it in GitHub Desktop.
compare shifting up and down
function shiftup(v::AbstractVector{T}, start, finish) where {T}
for i in finish:-1:start
@inbounds v[i+1] = v[i]
end
end
function shiftup4(v::AbstractVector{T}, start, finish) where {T}
n = finish - start
q, r = fldmod(n, 4)
@inbounds for i in finish-3:-4:start+r
v[i+4] = v[i+3]
v[i+3] = v[i+2]
v[i+2] = v[i+1]
v[i+1] = v[i]
end
if !iszero(r)
@inbounds for i in start+r:-1:start
v[i+1] = v[i]
end
end
end
"""
shiftdown(v, start>1, finish<=length(v))
shift contents of Vector from start through finish down by 1 position
"""
function shiftdown(v::AbstractVector{T}, start, finish) where {T}
for i in start:finish
@inbounds v[i-1] = v[i]
end
end
function shiftdown4(v::AbstractVector{T}, start, finish) where {T}
n = finish - start
q, r = fldmod(n, 4)
@inbounds for i in start:4:finish-r
v[i-1] = v[i]
v[i] = v[i+1]
v[i+1] = v[i+2]
v[i+2] = v[i+3]
end
if !iszero(r)
@inbounds for i in finish-r:finish
@inbounds v[i+1] = v[i]
end
end
end
using BenchmarkTools
v = sort(rand(10:990, 2048));
v1 = deepcopy(v);
v2 = deepcopy(v);
v3 = deepcopy(v);
v4 = deepcopy(v);
start = 1000;
finish = start + 250;
v1t = @belapsed shiftup($v1, $start, $finish);
v2t = @belapsed shiftup4($v2, $start, $finish);
v3t = @belapsed shiftdown($v3, $start, $finish);
v4t = @belapsed shiftdown4($v4, $start, $finish);
inanos(t) = round(Int, t * 1_000_000_000);
t1 = inanos(v1t);
t2 = inanos(v2t);
t3 = inanos(v3t);
t4 = inanos(v4t);
ups = (shiftup=t1, shiftup4=t2)
downs = (shiftdown=t3, shiftdown4=t4)
ratios = round.(Tuple(ups) .// Tuple(downs), sigdigits=2)
#=
julia> ups = (shiftup=t1, shiftup4=t2)
(shiftup = 62, shiftup4 = 30)
julia> downs = (shiftdown=t3, shiftdown4=t4)
(shiftdown = 18, shiftdown4 = 21)
julia>
julia> ratios = round.(Tuple(ups) .// Tuple(downs), sigdigits=2)
(3.4, 1.4)
=#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment