后钩函数,后处理并通过所有返回 [英] Post-hook a function, post-process and pass through all returns
问题描述
我有一个摘机后函数,它自己接收一些数据,对另一个函数的引用以及...
中该任意函数的参数.在引用的函数返回后,此函数会进行一些后处理.为了简单起见,我们只记录时间:
I have a post-hook function that receives some data for itself, reference to another function and arguments for that arbitrary function in ...
. This function does some post-processing, after referenced function returns. For simplicity let's just note time:
function passthrough(tag, func, ...)
metric1[tag] = os.time()
func(...)
metric2[tag] = os.time()
end
由于我需要后处理,所以我不能立即return func(...)
,而且我事先也不知道会有多少回报.完成后处理后,如何传递这些退货?
Since I need to postprocess, I can't immediately return func(...)
and I don't know in advance how many returns there will be. How can I passthrough those returns after I'm done with post-processing?
到目前为止,我只能想到在local results = { func(...) }
中进行包装调用,然后使用return unpack(results)
或创建一个后处理器工厂,该工厂将生成后处理闭包,并将所有必要的数据作为上值:
So far I can think only of packing call in local results = { func(...) }
and then using return unpack(results)
or making a postprocessor factory that'd generate postprocessing closure with all necessary data as upvalues:
local function generate_postprocessor(tag)
return function(...)
metric2[tag] = os.time()
return ...
end
end
function passthrough2(tag, func, ...)
metric1[tag] = os.time()
return generate_postprocessor(tag)(func(...))
end
但是,考虑到大量的迭代和应用程序的实时性,这两种方法都会带来一些不希望的开销.有没有更简单的东西?
However, both those approaches would introduce some overhead that is undesirable, considering high amount of iterations and real-time nature of application. Is there anything simpler?
推荐答案
您不需要闭包.无论如何,在调用闭包生成器之前都会调用func
.您只需要一个将其参数直接传递到其返回值的函数,即可为您的第二个标记提供一个连接点:
You don't need the closure. func
is called before calling your closure generator anyway. You just need a function that passes its arguments straight through to its return values to give you a hook point for your second tag:
function passthrough_return(tag, ...)
metric2[tag] = os.time()
return ...
end
function passthrough(tag, func, ...)
metric1[tag] = os.time()
return passthrough_return(tag, func(...))
end
您仍然要承担额外的函数调用的开销,但这比创建闭包或表要好得多,而且远少于预处理前后的开销.
You're still getting the overhead of an extra function call, but that's better than creating a closure or a table and far less than the overhead of your pre/post processing.
这篇关于后钩函数,后处理并通过所有返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!