Skip to content

Instantly share code, notes, and snippets.

@Katharsas
Last active Sep 28, 2021
Embed
What would you like to do?
MemoryBenchmark
-- these numbers can be adjusted to increase memory usage
-- numberOfEntries must always be bigger than numberOfSubEntries
numberOfEntries = 100000
numberOfSubEntries = 100
bigtable = {}
--------------------------------
-- SETUP
--------------------------------
-- Fills table with <numberOfEntries> entries, see createEntry()
function setup()
for i=1, numberOfEntries, 1 do
bigtable[i] = createEntry()
end
end
-- Each entry contains all numbers from 0 to <numberOfSubEntries> once, starting at a random number
function createEntry()
local entry = {};
local randomNumber = math.random(0, numberOfSubEntries - 1)
for i=1, numberOfSubEntries, 1 do
entry[i] = (randomNumber + i) % numberOfSubEntries
end
return entry
end
--------------------------------
-- BENCHMARKS
--------------------------------
-- Inside each entry, find the index where the zero is, and we create useless sum to check if randomness is properly distributed
-- Purpose: Test Table Iteration
function benchmark_find_sum()
local uselessSum = 0.0
local averageIndexWhereZeroIsFound = (numberOfSubEntries / 2) + 0.5
for i=1, numberOfEntries, 1 do
local currentEntry = bigtable[i]
for j=1, numberOfSubEntries, 1 do
if currentEntry[j] == 0 then
uselessSum = uselessSum + (j - averageIndexWhereZeroIsFound)
end
end
end
end
-- Randomly select pairs of entries that are opposite (if the table was a ring) and for those entries switch a bunch of subEntries (numbers)
-- Purpose: Test Non-Predictable bTable Read and Write
function benchmark_switch_entries()
local randomIndexStart = math.random(0, numberOfEntries - 1)
-- we select a 10th of all entries for doing this, starting at a random offset
for i=1, (numberOfEntries/10), 1 do
local indexA = randomIndexStart + (i * 10) + ((i * 31) % 97) -- slightly randomize so CPU cannot possibly predict access pattern
indexA = (indexA % numberOfEntries) + 1 -- make sure we wrap over back to zero when number is bigger than table size
local indexB = ((indexA + (numberOfEntries / 2)) % numberOfEntries) + 1
local entryA = bigtable[indexA]
local entryB = bigtable[indexB]
-- we switch every tenth number
for j=1, numberOfSubEntries, 10 do
local temp = entryA[j]
entryA[j] = entryB[j]
entryB[j] = temp
end
end
end
--------------------------------
-- RUN
--------------------------------
function runAndTime(name, fn, iterations)
start_time = os.time()
for i=1, iterations, 1 do
fn()
end
end_time = os.time()
elapsed_time = end_time - start_time
print(name.." - Time (sec): "..elapsed_time)
end
math.randomseed(os.time())
runAndTime("Setup", setup, 1) -- Lua.exe uses 220MB after setup
runAndTime("Benchmark 'Find' ", benchmark_find_sum, 10)
runAndTime("Benchmark 'Switch'", benchmark_switch_entries, 200)
print("Finished.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment