Skip to content

Instantly share code, notes, and snippets.

@raffecat
Created August 8, 2021 10:40
Show Gist options
  • Save raffecat/cb2a01ef1b5bbc559761cef971a35991 to your computer and use it in GitHub Desktop.
Save raffecat/cb2a01ef1b5bbc559761cef971a35991 to your computer and use it in GitHub Desktop.
Effect of cache-unfriendly array access in python
import time
import random
size = 1000000 # more zeros, more difference
nums = list(range(size))
inds = list(range(size))
# reset cache
sum(nums)
sum(inds)
# sum in memory order
st = time.time()
total = 0
for i in inds:
total += nums[i]
print(total, (time.time() - st)*1e6)
# randomize indexes
random.shuffle(inds)
# reset cache
sum(nums)
sum(inds)
# sum in random order
st = time.time()
total = 0
for i in inds:
total += nums[i]
print(total, (time.time() - st)*1e6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment