lua中的os.clock()返回错误值

问题描述 投票:0回答:1

我在lua中使用os.clock来测量函数的工作时间。我添加如下调试日志

test = function()
  print(">>>>>>>>start record id: ", record_id, "clock: ", os.clock())

  ...
  body
  ...

  print(">>>>>>>>end record id: ", record_id, "clock: ", os.clock())
end

我还使用

<your commadn> | ts "[%Y-%m-%d %H:%M:%S]"
来监视输出控制台。

在监视输出控制台时,我发现

ts
命令中的时间戳与lua中的
os.clock()
结果不同。

[2024-07-01 22:46:29] >>>>>>>>start record id:  2   clock:  0.143632
[2024-07-01 22:46:29] >>>>>>>>end record id:    2   clock:  0.152762
[2024-07-01 22:46:29] >>>>>>>>start record id:  3   clock:  0.152998
...
...
[2024-07-01 22:50:25] >>>>>>>>end record id:    3639    clock:  48.124877
[2024-07-01 22:50:25] >>>>>>>>start record id:  3640    clock:  48.125138
[2024-07-01 22:50:25] >>>>>>>>end record id:    3640    clock:  48.137237

按照上面的结果日志,要记录 3639 条记录,

ts
命令需要 4 分钟才能完成,但
os.clock()
只需要 48 秒。

我对

os.clock()
结果有误解吗?

预计 我只是想知道我的系统需要多少时间来记录 1 条记录。因为它非常快所以我使用

os.clock()
但结果让我困惑

lua timestamp
1个回答
0
投票

LuaSocket 似乎是一个很好的答案:https://w3.impa.br/~diego/software/luasocket/socket.html#gettime

您可以使用 LuaPosix 获得更精确的计时:https://luaposix.github.io/luaposix/modules/posix.time.html#clock_gettime但对于某些人来说我无法让它在我的机器上工作(

clock_gettime
函数返回一个数字而不是带有秒和纳秒的表)。所以LuaSocket可能是一个更安全的选择。

使用 LuaSocket:

local socket = require('socket')

test = function()
  local t = socket.gettime()
  print(">>>>>>>>start record id: ", record_id)

  ...
  body
  ...

  print(">>>>>>>>end record id: ", record_id, "time taken: ", socket.gettime() - t)
end

使用 LuaPosix:

local posix = require('posix')

test = function()
  print(">>>>>>>>start record id: ", record_id)
  local t = posix.clock_gettime(0)

  ...
  body
  ...

  local t2 = posix.clock_gettime(0)

  local elapsed_time = end_time.tv_sec - start_time.tv_sec + (end_time.tv_nsec - start_time.tv_nsec)

  print(">>>>>>>>end record id: ", record_id, "time taken: ", elapsed_time)
end
© www.soinside.com 2019 - 2024. All rights reserved.