|Portada|Blog|Space|
function test_range(n, times)
    local arr, res = {}, {}
    local times_res = {}
    for i = 1, n do arr[i] = math.random() end
    for t = 1, times do
        local sum = 0
        local t1 = os.clock()
        for j = 1, 1000 do
            for i = 1, n do
                sum = sum + arr[i]
            end
        end
        local t2 = os.clock() - t1
        res[#res+1] = sum
        times_res[#times_res+1] = 1e9 * t2 / n / 1000
    end
    return times_res, res
end

function test_ipairs(n, times)
    local arr, res = {}, {}
    local times_res = {}
    for i = 1, n do arr[i] = math.random() end
    for t = 1, times do
        local sum = 0
        local t1 = os.clock()
        for j = 1, 1000 do
            for i, v in ipairs(arr) do
                sum = sum + v
            end
        end
        local t2 = os.clock() - t1
        res[#res+1] = sum
        times_res[#times_res+1] = 1e9 * t2 / n / 1000
    end
    return times_res, res
end

function test_pairs(n, times)
    local arr, res = {}, {}
    local times_res = {}
    for i = 1, n do arr[i] = math.random() end
    for t = 1, times do
        local sum = 0
        local t1 = os.clock()
        for j = 1, 1000 do
            for i, v in pairs(arr) do
                sum = sum + v
            end
        end
        local t2 = os.clock() - t1
        res[#res+1] = sum
        times_res[#times_res+1] = 1e9 * t2 / n / 1000
    end
    return times_res, res
end

function stats(datas)
    local res = {sum=0}
    for k, v in ipairs(datas) do
        if not res.min or v < res.min then res.min = v end
        if not res.max or v > res.max then res.max = v end
        res.sum = res.sum + v
    end
    res.avg = res.sum / #datas
    return res
end

local st = stats(test_pairs(1000, 100))
print('time in ns/#t', st.min, st.avg, st.max)