FuncDiff: Quick drop-in pure function benchmark snippet

Made this for a friend earlier this year.

Intended for quick use, this module is a minimal implementation after taking inspiration from John Carmack’s idea of parallel implementation of functions, particularly if you are looking to optimise more performance out of your code.

This snippet lets you provide the functions you want to run, the function index for which you wish to return the results of, and then providing the original intended arguments via ...

This tool is intended to work with pure functions, ones which only manipulate data within its scope.

Whilst available to copy here for convenience, it is also available as the first snippet in my luau-util repo, where I intend to share & maintain other luau nicknacks in the future.

--!strict
--!optimize 2
--!native

-- FuncDiff:
-- Transparently benchmark a given array of pure functions.
-- Intended for quick drop-ins whilst optimizing your own code.
-- Crazyblox 2025

return function (
    Funcs: { [number]: (...any) -> (...any) },  -- Provide functions as an array
    ReturnIndex: number,                        -- Choose which function you want to return data from
    ...                                         -- Provided arguments for the function
): ( ...any )
    local FuncTimes: { [number]: number } = {}
    local FuncOuts: { [number]: { any } } = {}
    -- Process functions in given order
    for i: number, Func: (...any) -> (...any) in Funcs do
        local start = os.clock()
        FuncOuts[i] = table.pack( Func( ... ) )
        FuncTimes[i] = os.clock() - start
    end
    -- Output results of function array
    print( `Function Times:\n{ table.concat( FuncTimes, "\n" ) }`
    -- Return values from specified function
    return table.unpack( FuncOuts[ ReturnIndex ] )
end
4 Likes