Lua剧情场景 - coroutine.resume导致帧率下降(或者我做错了)

我尝试使用 Lua 中的协程来实现剪辑场景,但是出现了 massive fps drop 的问题。

我真的不知道为什么,但是 coroutine.resume 会使我的程序减速,从 5000 fps(完全不进行任何渲染)降到在 event coroutine 不死亡的情况下(例如不断地进行 resume)的 300-350 fps。当 event 变得死亡时,fps 返回正常。

我认为协程不能如此缓慢,这可能是由于我的 event.lua/eventManager.lua 代码中存在问题,或者我的测量 fps 的方式不正确,或者我做的一切都非常糟糕。

Event.lua

function event()
    print("Event started")
    -- 最简单的形式
    for i = 1,1000 do
        coroutine.yield()
    end
    --[[ 等待 5 秒钟
    local wait = 0.0
    print("Waiting 5 sec")
    while wait < 5.0 do
        wait = wait + coroutine.yield()
    end
    --]]
    --[[ 然后播放声音
    local alarmSound = SoundsManager.getSound("sounds/alarm.ogg")
    alarmSound:play()
    while alarmSound:isPlaying() do
          coroutine.yield()
    end
    --]]
    print("Event ended")
end

FPS.lua

local FPS =
{
   fps = 0,
   lastFPS = 0,
   framesTime = 0.0
}

function FPS.render(frameDelta)
    FPS.fps = FPS.fps + 1
    FPS.framesTime = FPS.framesTime + frameDelta
    if FPS.framesTime >= 1.0 then
       if FPS.fps ~= FPS.lastFPS then
          print("[FPS] ".. FPS.fps)
          FPS.lastFPS = FPS.fps
       end
       FPS.framesTime = 0.0
       FPS.fps = 0
    end
end

return FPS

EventsManager.lua

require "event"
local EventsManager = {}

function EventsManager.init()
   EventsManager.event = coroutine.create(event)
end

function EventsManager.update(frameDelta)
    if coroutine.status(EventsManager.event) ~= 'dead' then
       coroutine.resume(EventsManager.event, frameDelta)
    end
end

return EventsManager

Main.lua

EventsManager = require "EventsManager"
FPS = require "FPS"

EventsManager.init()

while true do
local frameDelta = getFrameDelta() -- 以某种方式获得 frameDelta
EventsManager.update(frameDelta)-- 关掉它 fps 就会好
--渲染场景
FPS.render(frameDelta)
end
点赞
用户988143
用户988143

我尝试了你的代码,只有 getFrameDelta 返回前一次和当前调用之间的时间差,而没有任何情景需要渲染。另外,我将等待时间更改为 10 秒。

local prevtime = os.clock()

local getFrameDelta = function()
    local curtime = os.clock()
    local framedelta = curtime - prevtime
    prevtime = curtime
    return framedelta
end

这是我的输出:

D:\Dev>lua5.1 LUAFPS.lua

Event started Waiting for .. 10

[FPS] 879171 [FPS] 882366 [FPS] 880471 [FPS] 882018 [FPS] 880513 [FPS] 881368 [FPS] 879623 [FPS] 881938 [FPS] 880498

Event ended

[FPS] 882053 [FPS] 1279909 [FPS] 1279631 [FPS] 1279899 [FPS] 1277089 [FPS] 1278399 [FPS] 1279005 [FPS] 1280125

所以,是的,协同程序确实会产生影响。每次协同程序 yield,它都必须记录函数离开的位置,以便在下一次调用时在该点上 resume。我认为这解释了我所看到的差距:800Kfps v 1200Kfps

话虽如此,我不明白为什么你需要用协同程序来计算 FPS。你已经有了在 FPS.render 中计算 FPS 的代码。只需在渲染场景后调用它即可,就像你现在所做的那样,只是跳过调用协同程序的事件管理器部分。

2013-08-26 16:22:52