Skip to content

Instantly share code, notes, and snippets.

@currymj
Last active August 25, 2018 01:05
Show Gist options
  • Save currymj/9dd398d8438798ca77495ca775581b2d to your computer and use it in GitHub Desktop.
Save currymj/9dd398d8438798ca77495ca775581b2d to your computer and use it in GitHub Desktop.
demonstrates that adding up certain values becomes much faster when an array is sorted, due to modern CPU branch prediction (see https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array)
function genlist()
arr = zeros(32768)
for i=1:length(arr)
arr[i] = rand(Int) % 256
end
arr
end
function processlist(arr)
sum = 0
for i=1:length(arr)
if arr[i] >= 128
sum += arr[i]
end
end
sum
end
x1 = genlist()
x2 = sort(x1)
# julia> using BenchmarkTools
# julia> @btime processlist($x1)
#124.064 μs (0 allocations: 0 bytes)
#1.55527e6
#julia> @btime processlist($x2)
#65.628 μs (0 allocations: 0 bytes)
#1.55527e6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment