Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. #=
  2. # follows code by Jacob Quinn in response to this
  3.  
  4. t = zeros(Int64, 100000);
  5.  
  6. @btime sum(t)
  7. 12.084 μs (0 allocations: 0 bytes)
  8. 0
  9.  
  10. t2 = reinterpret(Int64, zeros(UInt64, 100000));
  11.  
  12. @btime sum(t2)
  13. 88.805 μs (0 allocations: 0 bytes)
  14. 0
  15. =#
  16.  
  17. using BenchmarkTools
  18.  
  19.  
  20. struct TVector{T, S} <: AbstractVector{T}
  21. x::Vector{S}
  22. end
  23.  
  24. Base.size(a::TVector) = size(a.x)
  25.  
  26. Base.IndexStyle(::Type{T}) where {T <: TVector} = Base.IndexLinear();
  27.  
  28. @inline function Base.getindex(A::TVector{T}, i::Int) where {T}
  29. @boundscheck checkbounds(A, i)
  30. @inbounds x = Core.bitcast(T, A.x[i])
  31. return x
  32. end
  33.  
  34.  
  35. function fast_reinterpret(::Type{T}, x::Array{V,1}) where {V,T}
  36. (sizeof(T) !== sizeof(V) || !(isbitstype(T) && isbitstype(V))) &&
  37. throw(ErrorException("Cannot reinterpret($T, Vector{$V})"))
  38. return TVector{T, V}(x)
  39. end
  40.  
  41.  
  42. #=
  43.  
  44. ivec = ones(Int64, 1_000_000);
  45. uvec = reinterpret(UInt64, ivec);
  46.  
  47. q = reinterpret(UInt64, ivec); eltype(q) === UInt64
  48. q = reinterpret(Float64, ivec); eltype(q) === Float64
  49.  
  50. @btime sum(reinterpret(UInt64, ivec));
  51. @btime sum(fast_reinterpret(UInt64, ivec));
  52.  
  53. uvec_base = reinterpret(UInt64, ivec);
  54. uvec_fast = fast_reinterpret(UInt64, ivec);
  55.  
  56. elapsed_base = @belapsed sum(uvec_base);
  57. elapsed_fast = @belapsed sum(uvec_fast);
  58.  
  59. relative_speed = round(elapsed_base / elapsed_fast, digits=1)
  60. 8.8
  61.  
  62. =#
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement