c++ - timing a function call as if-statement condition in cpp -


i have function , gets called condition in if-statements, , interested time these calls.

i wonder if there way timing in 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); 

you can write function wraps function have:

#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; } 

simple exercise:

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";     } } 

you can wrap function takes arguments. simple lambda expression:

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";     } } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -