gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:17:35 25 4
gpt4 key购买 nike

我有一个函数,有时它会作为 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";
}
}

关于c++ - 将函数调用计时为 cpp 中的 if 语句条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29943211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com