Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function create_objects(num_objects)
- local objects = {}
- for i = 1, num_objects do
- objects[i] = { value = i }
- end
- return objects
- end
- local function shuffle(array)
- local rand = math.random
- local len = #array
- for i = len, 2, -1 do
- local j = rand(1, i)
- array[i], array[j] = array[j], array[i]
- end
- end
- local function access_objects(objects, indices, num_accesses)
- local start_time = os.clock()
- for i = 1, num_accesses do
- local obj = objects[indices[(i % #indices) + 1]]
- obj.value = obj.value + 1 -- Perform some operation on the object
- end
- local end_time = os.clock()
- return end_time - start_time
- end
- local num_objects = 1000000 -- Number of objects
- local num_accesses = 10000000 -- Number of accesses
- local objects = create_objects(num_objects)
- local indices_contiguous = {}
- local indices_random = {}
- for i = 1, num_objects do
- indices_contiguous[i] = i
- indices_random[i] = i
- end
- shuffle(indices_random)
- local time_random = access_objects(objects, indices_random, num_accesses)
- print("Time taken for randomized access: " .. time_random .. " seconds")
- local time_contiguous = access_objects(objects, indices_contiguous, num_accesses)
- print("Time taken for contiguous access: " .. time_contiguous .. " seconds")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement