Zamiel

Lua Benchmark Mod 3

Mar 9th, 2022 (edited)
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. -- +-----------------+
  2. -- | Benchmark Mod 2 |
  3. -- | by Zamiel |
  4. -- +-----------------+
  5.  
  6. -- This is a mod that will benchmark two different functions to calculate how much more efficient
  7. -- one function is over the other.
  8.  
  9. local socket = require("socket")
  10. local constants = require("constants")
  11.  
  12. local mod = RegisterMod("test-benchmark", 1)
  13.  
  14. -- Benchmark configuration
  15. local NUM_TRIALS_PER_FUNCTION = 100000
  16. local THRESHOLD_IN_SECONDS = 0.001 -- 1 millisecond
  17.  
  18. -- Variables
  19. local enabled = true
  20. local totalTimeTaken = 0
  21. local i = 0
  22.  
  23. -- ModCallbacks.MC_POST_RENDER (2)
  24. function mod:postRender()
  25. if not enabled then
  26. return
  27. end
  28.  
  29. i = i + 1
  30.  
  31. local elapsedTimeSeconds1 = mod:GetExecutionTimeInSeconds(mod.Function1)
  32. local elapsedTimeSeconds2 = mod:GetExecutionTimeInSeconds(mod.Function2)
  33.  
  34. local difference = elapsedTimeSeconds2 - elapsedTimeSeconds1
  35. totalTimeTaken = totalTimeTaken + difference
  36. if totalTimeTaken >= NUM_TRIALS_PER_FUNCTION * THRESHOLD_IN_SECONDS then
  37. Isaac.DebugString("i = " .. tostring(i))
  38. enabled = false
  39. return
  40. end
  41.  
  42. if i % 10 == 0 then
  43. Isaac.DebugString("On invocation: " .. tostring(i))
  44. Isaac.DebugString("Total time taken: " .. tostring(totalTimeTaken))
  45. Isaac.DebugString("Total time needs to be: " .. tostring(NUM_TRIALS_PER_FUNCTION * THRESHOLD_IN_SECONDS))
  46. end
  47. end
  48.  
  49. function mod:GetExecutionTimeInSeconds(func)
  50. local startTimeSeconds = socket:gettime()
  51. for i = 1, NUM_TRIALS_PER_FUNCTION do
  52. func()
  53. end
  54. local endTimeSeconds = socket:gettime()
  55.  
  56. return endTimeSeconds - startTimeSeconds
  57. end
  58.  
  59. -- Faster function
  60. function mod:Function1()
  61. local gameFrameCount = constants.GAME:GetFrameCount()
  62. return gameFrameCount
  63. end
  64.  
  65. -- Slower function
  66. function mod:Function2()
  67. local game = Game()
  68. local gameFrameCount = game:GetFrameCount()
  69. return gameFrameCount
  70. end
  71.  
  72. mod:AddCallback(ModCallbacks.MC_POST_RENDER, mod.postRender)
  73.  
Advertisement
Add Comment
Please, Sign In to add comment