API 测量在函数中花费的时间的设计

API design for measure time spent in a function

如果您想要一种方法来衡量在可组合性、易用性和清洁方面花费在特定 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...) 无效的退化情况。

另一个注意事项:可以在 timedCall returns 值之前将打印输出硬编码到 stderr,但是让选项对时间测量做一些其他事情是很好的。对于最后两个,这是 fon_completed.

的正确顺序

我发现选项 2 最有用:

  • 返回return值,直接使用
  • 通知回调可以使用结果打印类似

    的内容

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

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