Created
August 8, 2021 10:40
-
-
Save raffecat/cb2a01ef1b5bbc559761cef971a35991 to your computer and use it in GitHub Desktop.
Effect of cache-unfriendly array access in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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