在 CPP 中将函数调用定时为 if 语句条件

timing a function call as if-statement condition in cpp

本文关键字:if 语句 条件 定时 函数调用 CPP      更新时间:2023-10-16

>我有一个函数,有时它在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 << "Yean";
    } else {
        std::cout << "Nayn";
    }
}

您还可以包装接受参数的函数。使用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 << "Yean";
    } else {
        std::cout << "Nayn";
    }
}