我需要计算我的函数经过的时间。现在我正在使用 std::clock 并且据我所知这是测量 CPU 时间,这可能与实时不同。
std::clock_t start;
double duration;
start = std::clock();
someFunctionToMeasure();
duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
Run Code Online (Sandbox Code Playgroud)
所以我想知道两件事
std::clock 究竟是如何工作的?它只是在计算该功能时测量CPU吗?
有没有更好的方法来测量计算我的函数所用的时间?
使用<chrono>,您需要的代码可能如下所示:
using clock = std::chrono::system_clock;
using sec = std::chrono::duration<double>;
// for milliseconds, use using ms = std::chrono::duration<double, std::milli>;
const auto before = clock::now();
someFunctionToMeasure();
const sec duration = clock::now() - before;
std::cout << "It took " << duration.count() << "s" << std::endl;
Run Code Online (Sandbox Code Playgroud)
注意:感谢霍华德对上述内容的有益评论。
如果您多次需要此代码段并且开始/结束大约是您调用的范围的入口和出口点someFunctionToMeasure(),则将其包装到一个实用程序类中可能会有意义,该类now()在构造函数和析构函数中进行两次调用。
只是想采用现代方法来计时任何可调用的 using<chrono>和std::invokeC++17 中的方便。适用于成员、lambdas 或自由函数,或任何其他可调用函数。
// Just for convenience
using Seconds = std::chrono::duration<double>;
// Measure how much time the given function takes to execute using chrono
// Pass the function name, then all relevant arguments, including the object as the first if it's a member function
template<typename Function, typename... Args>
Seconds measure(Function&& toTime, Args&&... a)
{
auto start{std::chrono::steady_clock::now()}; // Start timer
std::invoke(std::forward<Function>(toTime), std::forward<Args>(a)...); // Forward and call
auto stop{std::chrono::steady_clock::now()}; // Stop timer
return (stop - start);
}
Run Code Online (Sandbox Code Playgroud)
这将返回函数执行所需的时间。如果您还需要返回值,您可以std::pair使用Seconds和 返回值创建一个,因为std::invoke将正确返回可调用返回的内容。
然后你可以像这样使用它:
auto t1 = measure(normalFunction);
auto t2 = measure(&X::memberFunction, obj, 4);
auto t3 = measure(lambda, 2, 3);
Run Code Online (Sandbox Code Playgroud)
分别在自由函数、成员函数和 lambda 上。