context.lua 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. local has_monitoring = minetest.get_modpath("monitoring")
  2. local mapblock_count, penalized_mapblock_count
  3. if has_monitoring then
  4. mapblock_count = monitoring.gauge("mesecons_debug_mapblock_count", "count of tracked mapblocks")
  5. penalized_mapblock_count = monitoring.gauge("mesecons_debug_penalized_mapblock_count", "count of penalized mapblocks")
  6. end
  7. -- blockpos-hash => context
  8. local context_store = {}
  9. mesecons_debug.get_context = function(pos)
  10. local blockpos = mesecons_debug.get_blockpos(pos)
  11. local hash = minetest.hash_node_position(blockpos)
  12. local ctx = context_store[hash]
  13. if not ctx then
  14. -- create a new context
  15. ctx = {
  16. -- usage in us
  17. micros = 0,
  18. -- average micros per second
  19. avg_micros = 0,
  20. -- time penalty
  21. penalty = 0,
  22. -- mtime
  23. mtime = minetest.get_us_time(),
  24. }
  25. context_store[hash] = ctx
  26. end
  27. -- update context
  28. -- whitelist flag
  29. ctx.whitelisted = mesecons_debug.whitelist[hash]
  30. return ctx
  31. end
  32. local timer = 0
  33. minetest.register_globalstep(function(dtime)
  34. timer = timer + dtime
  35. if timer < 1 then return end
  36. timer=0
  37. local penalized_count = 0
  38. local now = minetest.get_us_time()
  39. local cleanup_time_micros = 300 * 1000 * 1000
  40. mesecons_debug.context_store_size = 0
  41. for hash, ctx in pairs(context_store) do
  42. local time_diff = now - ctx.mtime
  43. if time_diff > cleanup_time_micros then
  44. -- remove item
  45. context_store[hash] = nil
  46. else
  47. -- calculate stuff
  48. ctx.avg_micros = math.floor((ctx.avg_micros * 0.9) + (ctx.micros * 0.1))
  49. ctx.micros = 0
  50. if ctx.avg_micros > mesecons_debug.max_usage_micros then
  51. -- add penalty
  52. ctx.penalty = math.min(ctx.penalty + 0.1, 20)
  53. elseif ctx.penalty > 0 then
  54. -- remove penalty (slowly)
  55. ctx.penalty = math.max(ctx.penalty - 0.01, 0)
  56. end
  57. mesecons_debug.context_store_size = mesecons_debug.context_store_size + 1
  58. if ctx.penalty > 0 then
  59. penalized_count = penalized_count + 1
  60. end
  61. end
  62. end
  63. if has_monitoring then
  64. mapblock_count.set(mesecons_debug.context_store_size)
  65. penalized_mapblock_count.set(penalized_count)
  66. end
  67. end)