Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. function expand_matrix(ms)
  2. T = eltype(eltype(ms))
  3. m2 = Matrix{T}(undef, 0, length(first(ms)))
  4. for i in eachindex(ms)
  5. m2 = [m2; ms[i]']
  6. end
  7. return m2
  8. end
  9.  
  10. function prealloc_matrix(ms)
  11. T = eltype(eltype(ms))
  12. l = length(first(ms))
  13. rows = Vector{Vector{T}}(undef, 0)
  14. sizehint!(rows, l)
  15. for r in ms
  16. push!(rows, r)
  17. end
  18. m2 = Matrix{T}(undef, length(rows), l)
  19. for i in eachindex(rows)
  20. m2[i,:] .= rows[i]
  21. end
  22. return m2
  23. end
  24.  
  25. julia> @benchmark prealloc_matrix(ms) setup=(ms=[zeros(10) for _ in 1:2000])
  26. BenchmarkTools.Trial:
  27. memory estimate: 290.48 KiB
  28. allocs estimate: 2012
  29. --------------
  30. minimum time: 54.812 μs (0.00% GC)
  31. median time: 60.610 μs (0.00% GC)
  32. mean time: 72.654 μs (12.13% GC)
  33. maximum time: 1.297 ms (94.20% GC)
  34. --------------
  35. samples: 10000
  36. evals/sample: 1
  37.  
  38. julia> @benchmark expand_matrix(ms) setup=(ms=[zeros(10) for _ in 1:2000])
  39. BenchmarkTools.Trial:
  40. memory estimate: 152.96 MiB
  41. allocs estimate: 7797
  42. --------------
  43. minimum time: 22.296 ms (8.96% GC)
  44. median time: 24.119 ms (9.42% GC)
  45. mean time: 25.338 ms (13.09% GC)
  46. maximum time: 80.244 ms (68.21% GC)
  47. --------------
  48. samples: 190
  49. evals/sample: 1
  50.  
  51. julia> @benchmark expand_matrix(ms) setup=(ms=[zeros(100) for _ in 1:2000])
  52. BenchmarkTools.Trial:
  53. memory estimate: 1.49 GiB
  54. allocs estimate: 7981
  55. --------------
  56. minimum time: 255.960 ms (9.87% GC)
  57. median time: 262.024 ms (10.06% GC)
  58. mean time: 271.074 ms (12.67% GC)
  59. maximum time: 320.406 ms (24.57% GC)
  60. --------------
  61. samples: 19
  62. evals/sample: 1
  63.  
  64. julia> @benchmark prealloc_matrix(ms) setup=(ms=[zeros(100) for _ in 1:2000])
  65. BenchmarkTools.Trial:
  66. memory estimate: 1.67 MiB
  67. allocs estimate: 2009
  68. --------------
  69. minimum time: 406.528 μs (0.00% GC)
  70. median time: 435.928 μs (0.00% GC)
  71. mean time: 496.345 μs (8.97% GC)
  72. maximum time: 42.289 ms (98.87% GC)
  73. --------------
  74. samples: 6744
  75. evals/sample: 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement