SungAli

SLua Timing effort.

Jun 7th, 2026
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 11.51 KB | None | 0 0
  1. --Debugging Tools: lead comment:   --[[ -> feature disabled  ---[[ -> feature enabled
  2.  
  3. ---[=[ Name, Version, and Description management.
  4. Name = `Ali's Performance Comparer`
  5. Version = "0.6"
  6. Desc = [[
  7. Personal Version
  8.  ]] .. `{if bit32.btest(ll.GetObjectPermMask(MASK_EVERYONE), PERM_COPY) then "Feel free to take a copy" else "" }`
  9.  
  10. ll.SetObjectName( `{Name}: {Version}` ); ll.SetObjectDesc( Desc ); ll.SetText( `{Name}: {Version}\n \n{Desc}`, vector(0.5,0.5,1), 1 )
  11. --]=]
  12.  
  13. --- Generally useful functions. Always enabled. Adds nothing to compiled code unless called.
  14.    function concat( ... ) -- Return stringized values as a comma separated sting. Avoid using tables so explicit nils are preserved.
  15.        local count = select("#", ...); if count == 0 then return "" end--if
  16.        local result = tostring(select(1, ...)); for i = 2, count do result ..= `, {tostring(select(i, ...))}` end--for
  17.        return result
  18.    end--concat
  19.  
  20.    local rawprint = print -- always enabled just in case some code is using rawprint to bypass the redirect below
  21. ---[[ Redirect print Debug channel to avoid spamming chat.  Must be enabled if DBG block below is enabled.
  22.    local function print(...) ll.Shout( DEBUG_CHANNEL, concat(...) )  end--print
  23. --]=]
  24.  
  25. ---[[ Send DBG messages to the Debug Channel to sync with error messages and avoid spamming Nearby Chat
  26.    local DBG_buffer = ""
  27.    local function rawDBG( msg ) ll.Shout( DEBUG_CHANNEL, msg ) end--rawDBG this function exist to allow redirecton of all DBG output to a single destination in one place
  28.  
  29.    local function DBGb( ... ) DBG_buffer ..= concat(...).."; "; end--DBGb  (Buffer message for output wiht next DBG or DBGs call, allows multiple messages on a line.)
  30.    local function DBGs( ... ) local n,l = debug.info(2, "nl"); rawDBG( `{ll.GetTimestamp()}: {l} {n}: {DBG_buffer} {concat(...)}` );DBG_buffer=""; ll.Sleep(0.2) end--DBG  (with timestamp) & Delay
  31.    local function DBG( ... ) local n,l = debug.info(2, "nl"); rawDBG( `{ll.GetTimestamp()}: {l} {n}: {DBG_buffer} {concat(...)}` ); DBG_buffer=""; end--DBG  (with timestamp)
  32.  
  33.    local function DBG_dump( label, val, lvl ) --dump any data structure
  34.        lvl = lvl or 0
  35.        local indent = string.rep( "  ", lvl )
  36.        local leader = indent .. `({typeof(label)}) {tostring(label)}: `
  37.        if lvl == 0 then  local n,l = debug.info(2, "nl"); leader =  `{ll.GetTimestamp()}: {l} {n}:\n` .. leader end--if (with timestamp)
  38.        local typ = typeof( val )
  39.        if typ == "table" then
  40.            rawDBG( `{leader}({typ}) {tostring(val)} `.."{" )
  41.            lvl += 1
  42.            for k,v in pairs(val) do DBG_dump( k, v, lvl ) end--for
  43.            rawDBG( indent .. "}" )
  44.        else rawDBG( `{leader}({typ}) {tostring(val)}` )
  45.        end--if
  46.    end--DBG_dump
  47.  
  48.  function DBG_dump_list( label, list )  local n,l = debug.info(2, "nl"); rawDBG( `{ll.GetTimestamp()}: {l} {n}: {label}:  {concat(unpack(list))}` ) end--dump a list (1D array) on one line.
  49.  
  50. function DBG_err( ... )
  51.    local n,l = debug.info(2, "nl")
  52.    rawDBG( `{ll.GetTimestamp()}: {l} {n}: Error Caught by xpcall`, ... )
  53.    rawDBG( debug.traceback( "Stack Trace", 2) )
  54. end--DBG_err
  55.  
  56. --[=[]]  --Switch to do-nothing dummy versions when above is disabled.
  57.    local function rawDBG() end--rawDBG disabled
  58.    local DBG, DBG_dump, DBG_dump_list = rawDBG, rawDBG, rawDBG --Other DBG functions disabled.
  59.    local DBG_err = print --don't disable error reporting entirely.
  60. --]=]
  61.  
  62. -->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code start <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  63. ----Constants/Parameters
  64. --usually a few large samples are better than many smaller ones. 10 milliseconds per sample is a good goal
  65. local sample_size   = 650  -- Adjust as needed to keep sample times between the clock granularity factor and the frame break threshold.
  66. local sample_count  = 50  -- Balance between the time you want to spend and needed precision of the measure.  10 to 100 is probably good for most uses.
  67.  
  68. local script_frame_time = 1/45 -- nominal time between script frames.  If a sample's time exceeds this value, frame break artifacts are present.
  69. local clock_granularity = 100e-6 -- 100 microseconds/tick
  70. local test_period_min, test_period_max = clock_granularity * 0.75, clock_granularity * 1.25 --  Script slice is supposedly 300.  Aiming for exactly (DBG 1) 2 ticks per slice.
  71. --local frame_break_threshold = script_frame_time * 0.9 --short frame breaks are possible. Low value passes fewer short breaks, Hi value allows lager sample_size.  Balance for best RSD @ sample_count.
  72. --local rejection_limit = sample_count * 2 --When trying to maximize sample size, rejections may pile up.
  73.  
  74. ----Variables
  75. local start, finish, overhead --os.clock values for a given test loop.
  76. --local test_start
  77. local times --an array of arrays for holding sample times.
  78. local rejections -- a count of samples rejected due to frame break.
  79.  
  80. ----Functions
  81. local function fmt(v, m, d) -- return value scaled by 10^m to d decimal places.
  82.     d = d or 6; m = m or 6 -- default to 6 places scaled by a million (for microseconds)
  83.     return string.format( `%.{d}f`, v*10^m )
  84. end--fmt
  85.  
  86. --using Sample Standard Deviantion vs Population Standard Deviation should give more consistent results if we vary our total samples.
  87. --contracted name because calling min_max_mean_and_normalized_sample_standard_deviaton( list ) is too freakin' much *grins*.
  88. local function MMMSSD( list ) -- return the Min, Max, Mean and the Normalized Sample Standard Deviation of the values in list.
  89.     local len = #list
  90.     local min, max, mean = math.huge, -math.huge, 0
  91.     for i = 1, len do
  92.         local v = list[i]
  93.         if v < min then min = v end--if
  94.         if v > max then max = v end--if
  95.         mean += v
  96.     end--for
  97.     mean /= len
  98.     local ssd = 0
  99.     for i = 1, len do
  100.         ssd += ( (list[i]-mean) / mean ) ^ 2
  101.     end--for
  102.     ssd /= len-1 --Change the divisor to just len if you want the Population SDev.
  103.     return min, max, mean, ssd
  104. end--MSSD
  105.  
  106. local function report( label ) --do sanity checks, adjust times, and report results
  107.     print( `\n{label} report:`)
  108.     for sample = 1, sample_count do times[sample] /= sample_size end--for
  109.     local min, max, mean, ssd = MMMSSD( times )
  110.     local lo_d, hi_d = mean-min, max-mean; local max_dev = if lo_d > hi_d then lo_d else hi_d
  111.     print( `Min= {fmt(min)} μs, Max= {fmt(max)} μs, Mean= {fmt(mean)} μs, NSSD= {fmt(ssd, 2)} %, MD= {fmt(max_dev)} μs, RSD= {math.floor( -math.log10(ssd) ) + 1}` )
  112.     return min, max, mean, ssd, max_dev
  113. end--report
  114.  
  115. local tests = {
  116.     { name = "Overhead", test = function() -- This first, do nothing, loop established a base time to subtract from test times to account for loop overhead.
  117.         local count, clk
  118.         repeat
  119.             ll.Sleep(0.01)
  120.             count, clk = 0, os.clock()
  121.             start = clk; while start == clk do start = os.clock() end--while --wait for a clock tick
  122.             local finish_min, finish_max = start + test_period_min, start + test_period_max
  123.                 repeat
  124.                     --do nothing
  125.                     count +=1;
  126.                 clk = os.clock(); until clk > finish_min
  127.                 if clk > finish_max then print( `test_period_exceeded: period= {fmt(clk-start)}μs count= {count}. Retrying.`) end-- if
  128.         until clk < finish_max
  129.         return (clk-start)/count
  130.     end}, -- Overhead
  131.     { name = "Null", test = function() --Null Test. This should return stats with near zero time estimates
  132.         local count, clk
  133.         repeat
  134.             ll.Sleep(0.01)
  135.             count, clk = 0, os.clock()
  136.             start = clk; while start == clk do start = os.clock() end--while --wait for a clock tick
  137.             local finish_min, finish_max = start + test_period_min, start + test_period_max
  138.                 repeat
  139.                     --do nothing
  140.                     count +=1;
  141.                 clk = os.clock(); until clk > finish_min
  142.                 if clk > finish_max then print( `test_period_exceeded: period= {fmt(clk-start)}μs count= {count}. Retrying.`) end-- if
  143.         until clk < finish_max
  144.         return (clk-start)/count - overhead
  145.     end}, --Null
  146.     { name = "DBG", test = function() --Debug Null Test.
  147.         local count, clk
  148.         repeat
  149.             ll.Sleep(0.01)
  150.             count, clk = 0, os.clock()
  151.             start = clk; while start == clk do start = os.clock() end--while --wait for a clock tick
  152.             local finish_min, finish_max = start + test_period_min, start + test_period_max
  153.                 repeat
  154.                     --do nothing
  155.                     count +=1;
  156.                 clk = os.clock(); until clk > finish_min
  157.                 if clk > finish_max then print( `test_period_exceeded: period= {fmt(clk-start)}μs count= {count}. Retrying.`) end-- if
  158.         until clk < finish_max
  159.         return (clk-start)/count
  160.     end}, --dbg
  161.     { name = "Test 1", test = function() --first actual performance test
  162.         local count, clk
  163.         repeat
  164.             ll.Sleep(0.01)
  165.             count, clk = 0, os.clock()
  166.             start = clk; while start == clk do start = os.clock() end--while --wait for a clock tick
  167.             local finish_min, finish_max = start + test_period_min, start + test_period_max
  168.                 repeat
  169.                     --Start code to test
  170.                     _ = ll.AxisAngle2Rot( vector(0,0,1), math.random()*TWO_PI )
  171.                     --End code to test
  172.                     count +=1;
  173.                 clk = os.clock(); until clk > finish_min
  174.                 if clk > finish_max then print( `test_period_exceeded: period= {fmt(clk-start)}μs count= {count}. Retrying.`) end-- if
  175.         until clk < finish_max
  176.         return (clk-start)/count - overhead
  177.     end}, -- Test 1
  178.     { name = "Test 2", test = function() --second performance test
  179.         local count, clk
  180.         repeat
  181.             ll.Sleep(0.01)
  182.             count, clk = 0, os.clock()
  183.             start = clk; while start == clk do start = os.clock() end--while --wait for a clock tick
  184.             local finish_min, finish_max = start + test_period_min, start + test_period_max
  185.                 repeat
  186.                     --Start code to test
  187.                     local t = math.random()*TWO_PI/2; _ = quaternion( 0,0, math.sin(t), math.cos(t) )
  188.                     --End code to test
  189.                     count +=1;
  190.                 clk = os.clock(); until clk > finish_min
  191.                 if clk > finish_max then print( `test_period_exceeded: period= {fmt(clk-start)}μs count= {count}. Retrying.`) end-- if
  192.         until clk < finish_max
  193.         return (clk-start)/count - overhead
  194.     end}, -- Test 2
  195. }
  196.  
  197. local function do_test( num )
  198.     times = {}
  199.     print( `\n\nStarting Test: {tests[num].name}`)
  200.     local sample = 1; while sample <= sample_count do
  201.         times[sample] = tests[num].test()
  202.         ll.SetText(`{tests[num].name} successful samples= {sample}.`, vector(0.5,1,0.5), 1 )
  203.         sample += 1
  204.     end--while
  205. end--do_test
  206.  
  207. ----Do it
  208. test_start = os.clock();
  209. print(
  210.     `\n\n    ----Testing with {sample_count} samples.----\n`..
  211.     "NSSD -> Normalized Sample Standard Deviation, MD -> Max Deviation, RSD -> estimated Reliable Significant Digits of the mean based on NSSD."
  212. )
  213.  
  214. do_test(1); _, _, overhead = report( tests[1].name ) -- establish overhead
  215. print(`overhead = {fmt(overhead)}`)
  216. for num = 2, #tests do do_test(num); report( tests[num].name ) end--for -- perform tests
  217.  
  218. ll.SetText( `{Name}: {Version}\n \n{Desc}`, vector(0.5,0.5,1), 1 )
  219.  
Advertisement
Add Comment
Please, Sign In to add comment