Search code examples
c++if-statementtimingc++-chrono

timing a function call as if-statement condition in cpp


I have a function and sometimes it gets called as a condition in if-statements, and I am interested to time exactly these calls.

I wonder if there is any way to do something like this for timing it 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);

Solution

  • You can write a function that wraps the function you already 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 also wrap a function that takes arguments. This is simple to do with a 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";
        }
    }