【问题标题】:API design for measure time spent in a function [closed]用于测量函数花费时间的 API 设计[关闭]
【发布时间】: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,但最好让选项对时间测量执行其他操作。对于最后两个,是fon_completed的正确顺序。

【问题讨论】:

  • 最后两个函数的用例是什么?既然您(可能)希望您的函数同步运行,为什么要传递回调?只是想看看我是否遗漏了什么。
  • @Victor,显然,第二个版本是启用,例如,打印出函数花费的时间。因此,对于一般可用性而言,第二个版本似乎即将推出,但我最喜欢第一个版本。
  • @jvd 不幸的是,当您在参数包之后放置这样的参数时,在某些编译器(尤其是较旧的编译器)上可能会有点混乱
  • 是的,我完全理解这一点。但这就是图书馆发展的乐趣,不是吗? :-)
  • 如果此timedCall 用于调试模式但未用于发布模式(即根本不测量),那么您需要返回值是f 调用的值。这使得只有选项 2 可行。

标签: c++ api-design


【解决方案1】:

我发现选项 2,加上将结果作为引用传递给 const,是最有用的:

  • 它给你返回值,所以可以直接使用
  • 通知回调可以使用结果来打印类似的东西

    "Processed %zu entries in %.7f seconds\n"

    对于不同的返回类型,operator()()可以使用多个重载的函数对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-13
    • 2014-05-25
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多