Skip to content

Instantly share code, notes, and snippets.

@haampie
Last active March 22, 2018 14:08
Show Gist options
  • Save haampie/fe17a363009d4f7aed555368afd5e944 to your computer and use it in GitHub Desktop.
Save haampie/fe17a363009d4f7aed555368afd5e944 to your computer and use it in GitHub Desktop.
Conversions
using BenchmarkTools
import Base: getindex
@inline function getindex(v::UnitRange{Int32}, i::Integer)
first(v) + Core.Intrinsics.trunc_int(Int32, i) - one(Int32)
end
function copy_via_broadcast!(x::AbstractVector{Ti}, r::UnitRange{Ti}) where {Ti}
x .= r
x
end
function copy_via_iterator!(x::AbstractVector{Ti}, r::UnitRange{Ti}) where {Ti}
@inbounds for (i, j) = enumerate(r)
x[i] = j
end
x
end
function via_loop!(x::AbstractVector{Ti}, r::UnitRange{Ti}) where {Ti}
value = r.start
@inbounds for i = 1 : length(r)
x[i] = value
value += one(Ti)
end
x
end
function bench(n = 5_000)
vec32 = Vector{Int32}(undef, n)
vec64 = Vector{Int64}(undef, n)
r32 = Int32(1) : Int32(n)
r64 = Int64(1) : Int64(n)
default_32 = @benchmark copyto!($vec32, $r32)
# default_64 = @benchmark copyto!($vec64, $r64)
loop_32 = @benchmark via_loop!($vec32, $r32)
# loop_64 = @benchmark via_loop!($vec64, Int64($n))
broadcast_32 = @benchmark copy_via_broadcast!($vec32, $r32)
# broadcast_64 = @benchmark copy_via_broadcast!($vec64, $r64)
iter_32 = @benchmark copy_via_iterator!($vec32, $r32)
# iter_64 = @benchmark copy_via_iterator!($vec64, $r64)
return default_32, loop_32, broadcast_32, iter_32
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment