Advertisement
Guest User

Untitled

a guest
Sep 15th, 2024
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. local function create_objects(num_objects)
  2. local objects = {}
  3. for i = 1, num_objects do
  4. objects[i] = { value = i }
  5. end
  6. return objects
  7. end
  8.  
  9. local function shuffle(array)
  10. local rand = math.random
  11. local len = #array
  12. for i = len, 2, -1 do
  13. local j = rand(1, i)
  14. array[i], array[j] = array[j], array[i]
  15. end
  16. end
  17.  
  18. local function access_objects(objects, indices, num_accesses)
  19. local start_time = os.clock()
  20. for i = 1, num_accesses do
  21. local obj = objects[indices[(i % #indices) + 1]]
  22. obj.value = obj.value + 1 -- Perform some operation on the object
  23. end
  24. local end_time = os.clock()
  25. return end_time - start_time
  26. end
  27.  
  28. local num_objects = 1000000 -- Number of objects
  29. local num_accesses = 10000000 -- Number of accesses
  30.  
  31. local objects = create_objects(num_objects)
  32.  
  33. local indices_contiguous = {}
  34. local indices_random = {}
  35. for i = 1, num_objects do
  36. indices_contiguous[i] = i
  37. indices_random[i] = i
  38. end
  39.  
  40. shuffle(indices_random)
  41.  
  42. local time_random = access_objects(objects, indices_random, num_accesses)
  43. print("Time taken for randomized access: " .. time_random .. " seconds")
  44.  
  45. local time_contiguous = access_objects(objects, indices_contiguous, num_accesses)
  46. print("Time taken for contiguous access: " .. time_contiguous .. " seconds")
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement