我有一个函数,有时会在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);
答案 0 :(得分:1)
您可以编写一个包含您已有功能的函数:
#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";
}
}