Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

script: add clock module #500

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

script: add clock module #500

wants to merge 1 commit into from

Conversation

myzhan
Copy link

@myzhan myzhan commented Aug 19, 2022

Tring to add a clock module, so I can write per-thread request rate limiter in lua, with the global delay function.

@myzhan
Copy link
Author

myzhan commented Aug 19, 2022

Aslo, I can use ffi.

local ffi = require("ffi")

ffi.cdef[[
    typedef long time_t;
    typedef int clockid_t;

    typedef struct timespec {
            time_t   tv_sec;        /* seconds */
            long     tv_nsec;       /* nanoseconds */
    } nanotime;
    int clock_gettime(clockid_t clk_id, struct timespec *tp);
]]

function get_current_time_in_ms()
    local pnano = ffi.new("nanotime[?]", 1)
    -- CLOCK_REALTIME  -> 0
    -- CLOCK_MONOTONIC -> 6
    ffi.C.clock_gettime(6, pnano)
    return pnano[0].tv_sec * 1000 + pnano[0].tv_nsec/1000000
end

function setup()
    local prev_time = get_current_time_in_ms()
end

local MAX_RPS = 2000
local current_rps = 0
local prev_time = 0

function delay()
    local now_ms = get_current_time_in_ms()
    local elapsed = now_ms - prev_time
    if elapsed > 1000 then
        prev_time = now_ms
        current_rps = 0
        return 0
    else
        current_rps = current_rps + 1
        if current_rps <= MAX_RPS then
            return 0
        end
        -- return sleep time in millis
        local sleep_time = 1000 - elapsed
        -- convert ffi's cdata into lua number
        return tonumber(sleep_time)
    end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant