将函数调用计时为 cpp 中的 if 语句条件

timing a function call as if-statement condition in cpp

我有一个函数,有时它会作为 if 语句中的条件被调用,我有兴趣精确计算这些调用的时间。

我想知道是否有任何方法可以在 cpp 中进行计时:

using watch = std::chrono::high_resolution_clock;
std::chrono::nanoseconds time(0);
if ( auto start = watch::now(); SOME_FUNCTION(); auto end = watch::now();)
{...}else{...}
time += (end - start);

您可以编写一个函数来包装您已有的函数:

#include <iostream>
#include <chrono>

using watch = std::chrono::high_resolution_clock;

template <class F>
auto measure_time(const F& f, std::chrono::nanoseconds& time) -> decltype(f()) {
    auto start = watch::now();
    auto return_value = f();
    auto end = watch::now();
    time += end - start;
    return return_value;
}

简单练习:

bool some_function() {
    return true;
}

int main() {
    std::chrono::nanoseconds time(0);

    if (measure_time(some_function, time)) {
        std::cout << "Yea\n";
    } else {
        std::cout << "Nay\n";
    }
}

您还可以包装一个带参数的函数。使用 lambda 表达式很简单:

void* some_other_function(void* v) {
    return v;
}

int main() {
    std::chrono::nanoseconds time(0);

    if (measure_time([]{ return some_other_function(0); }, time)) {
        std::cout << "Yea\n";
    } else {
        std::cout << "Nay\n";
    }
}