You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Lua中os.clock()返回值与实际耗时不符的疑问

问题解答

你确实误解了os.clock()的返回值——它统计的是你的Lua程序实际占用CPU运算的时间,不是从开始到结束的实际流逝时间(也就是墙钟时间,ts命令显示的就是这个)。

为什么会有这么大的差异?

ts命令的时间戳记录的是真实的时间流逝,从22:46到22:50确实是4分钟左右。而os.clock()的48秒,是你的程序在这4分钟里真正让CPU跑运算的总时间。剩下的时间里,程序可能在做这些事:

  • 等待数据库查询、文件读写、网络请求这类IO操作(此时CPU没在执行你的代码)
  • 被操作系统调度到后台,CPU分给了其他进程
  • 主动休眠或者等待某个信号

如何获取单条记录的实际耗时?

如果要测量单条记录从开始到结束的真实流逝时间(包含等待),你需要用墙钟时间相关的API:

方案1:使用LuaSocket的高精度时间(推荐,精度到微秒)

需要先安装LuaSocket库,然后用socket.gettime()获取当前时间:

local socket = require("socket")

test = function()
  local start_real = socket.gettime()
  local start_cpu = os.clock()

  -- 你的业务代码
  ...

  local end_real = socket.gettime()
  local end_cpu = os.clock()
  
  print(">>>>>>>>start record id: ", record_id, "real_time: ", start_real, "cpu_time: ", start_cpu)
  print(">>>>>>>>end record id: ", record_id, "real_time: ", end_real, "cpu_time: ", end_cpu)
  print(">>>>>>>>record id:", record_id, "实际耗时:", end_real - start_real, "CPU耗时:", end_cpu - start_cpu)
end

方案2:原生Lua实现(无需额外库,精度到毫秒)

如果无法安装LuaSocket,可以用os.date组合出高精度时间:

local function get_real_time()
  local t = os.date("*t")
  -- 转换为秒数,加上微秒部分
  return t.hour * 3600 + t.min * 60 + t.sec + tonumber(os.date("%f")) / 1000000
end

test = function()
  local start_real = get_real_time()
  local start_cpu = os.clock()

  -- 你的业务代码
  ...

  local end_real = get_real_time()
  local end_cpu = os.clock()
  
  print(">>>>>>>>start record id: ", record_id, "real_time: ", start_real, "cpu_time: ", start_cpu)
  print(">>>>>>>>end record id: ", record_id, "real_time: ", end_real, "cpu_time: ", end_cpu)
  print(">>>>>>>>record id:", record_id, "实际耗时:", end_real - start_real, "CPU耗时:", end_cpu - start_cpu)
end

两种时间的适用场景

  • os.clock()的CPU时间:适合衡量纯运算逻辑的性能,比如算法优化后的效率提升,排除IO、调度等外部因素的影响
  • 墙钟时间:适合衡量业务操作的真实耗时,比如用户感知到的等待时间,包含所有等待和运算的总时间

内容的提问来源于stack exchange,提问作者LV_Embedded

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 13:37:06