From daadb0e51895059922f90d77b19f7f4bc94f1655 Mon Sep 17 00:00:00 2001 From: sfwn Date: Thu, 22 Feb 2024 15:53:30 +0800 Subject: [PATCH] ensure_time: use UTC directly, drop regex for timezone to speedup; add benchmark (#55) --- conf/ds/time.lua | 19 ++++++++----------- conf/ds/time_bench_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 11 deletions(-) create mode 100644 conf/ds/time_bench_test.go diff --git a/conf/ds/time.lua b/conf/ds/time.lua index 0ed03e5c6..8410d5dcc 100644 --- a/conf/ds/time.lua +++ b/conf/ds/time.lua @@ -10,19 +10,16 @@ function ensure_time(_, timestamp, record) local sec = math.floor(timestamp) local nsec = math.floor((timestamp - sec) * 1e9) - -- 将时间戳转换为指定格式的日期字符串 - local zone = os.date("%z", timestamp) - zone = tostring(zone) - if string.len(zone) > 0 then - -- add `:` to zone, change +0800 to +08:00 - zone = tostring(zone):gsub("^(%+)(%d%d)(%d%d)$", "%1%2:%3") - else - zone = "Z" - end + -- 将时间戳转换为指定格式的日期字符串, zone=UTC + local dateStr = os.date("!%Y-%m-%dT%H:%M:%S", sec) .. string.format(".%09d", nsec) .. "Z" - -- 生成日期字符串 - local dateStr = os.date("%Y-%m-%dT%H:%M:%S", sec) .. string.format(".%09d", nsec) .. zone record[timeField] = dateStr return 2, timestamp, record end + +-- -- invoke ensure_time for benchmark +-- local socket = require("socket") +-- local record = { time = "2021-01-01T00:00:00Z" } +-- local _, _, record = ensure_time(nil, socket.gettime(), record) +-- print(record["time"]) diff --git a/conf/ds/time_bench_test.go b/conf/ds/time_bench_test.go new file mode 100644 index 000000000..a0bd2bf61 --- /dev/null +++ b/conf/ds/time_bench_test.go @@ -0,0 +1,27 @@ +package ds_test + +import ( + "embed" + "os" + "os/exec" + "testing" +) + +//go:embed time.lua +var timeLua embed.FS + +func Benchmark_lua_ensure_time(b *testing.B) { + f, _ := os.CreateTemp("/tmp", "") + bytes, _ := timeLua.ReadFile("time.lua") + f.Write(bytes) + // write from embed.FS to file + for i := 0; i < b.N; i++ { + cmd := exec.Command("lua", f.Name()) + //cmd.Stdout = os.Stdout + //cmd.Stderr = os.Stdout + err := cmd.Run() + if err != nil { + b.Fatal(err) + } + } +}