Skip to content

Commit

Permalink
ensure_time: use UTC directly, drop regex for timezone to speedup; ad…
Browse files Browse the repository at this point in the history
…d benchmark (#55)
  • Loading branch information
sfwn authored Feb 22, 2024
1 parent 4f0d3cf commit daadb0e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
19 changes: 8 additions & 11 deletions conf/ds/time.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
27 changes: 27 additions & 0 deletions conf/ds/time_bench_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}

0 comments on commit daadb0e

Please sign in to comment.