【发布时间】:2020-09-23 21:58:00
【问题描述】:
如果您想要一种衡量在特定 Callable f 中花费的时间的方法,在可组合性、易用性和干净的调用站点方面,以下哪个 API:s 最干净。
/** Calls `f` with args and returns a TimedResult carrying
* the return value of `f`, and the real time spent in `f`.
*/
template<class Function, class... T>
auto timedCall(Function&& f, T&&... args)
或者
/** Calls `f` with args and returns its result. Before returning the
* value, it invokes onCompleted(t), where `t` is the time spent in `f`.
*/
template<class OnCompleted, class Function, class... T>
auto timedCall(OnCompleted&& on_completed, Function&& f, T&&... args)
甚至
/** Calls `f` with args. When the function returns, `on_completed(t, std::move(res))`
* is called, where `t` is the time spent in `f`, and `res` is its return value.
*/
template<class OnCompleted, class Function, class... T>
void timedCall(OnCompleted&& on_completed, Function&& f, T&&... args)
注意:为简洁起见,省略了 f(args...) 为 void 的退化情况。
另一个注意事项:可以在 timedCall 返回值之前将打印输出硬编码到 stderr,但最好让选项对时间测量执行其他操作。对于最后两个,是f和on_completed的正确顺序。
【问题讨论】:
-
最后两个函数的用例是什么?既然您(可能)希望您的函数同步运行,为什么要传递回调?只是想看看我是否遗漏了什么。
-
@Victor,显然,第二个版本是启用,例如,打印出函数花费的时间。因此,对于一般可用性而言,第二个版本似乎即将推出,但我最喜欢第一个版本。
-
@jvd 不幸的是,当您在参数包之后放置这样的参数时,在某些编译器(尤其是较旧的编译器)上可能会有点混乱
-
是的,我完全理解这一点。但这就是图书馆发展的乐趣,不是吗? :-)
-
如果此
timedCall用于调试模式但未用于发布模式(即根本不测量),那么您需要返回值是f调用的值。这使得只有选项 2 可行。
标签: c++ api-design