在 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 << "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";
}
}
相关文章:
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- c++:定义if语句中的模板
- C++嵌套的 If 语句中,它无法按预期工作
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 需要有关此 if 语句的帮助
- 转换器练习:跳过 if 语句和 if 语句
- 避免在 C++ 中的 if 语句中递增
- 如果仍然不满足要求,如何使 if 语句重复?
- do while 循环中的 if 语句以 yes 或 no 结尾
- 为什么在此C++代码中触发此 if 语句?
- 如何基于平台在制作文件中制作if语句?
- 在 if 语句中使用 GetKeyState 时,它会跳过条件
- C++ If 语句,从其他语句重复