Measuring execution time of a function in C++

后端 未结 11 889
小鲜肉
小鲜肉 2020-11-22 12:59

I want to find out how much time a certain function takes in my C++ program to execute on Linux. Afterwards, I want to make a speed comparison . I saw sever

11条回答
  •  无人共我
    2020-11-22 13:28

    You can have a simple class which can be used for this kind of measurements.

    class duration_printer {
    public:
        duration_printer() : __start(std::chrono::high_resolution_clock::now()) {}
        ~duration_printer() {
            using namespace std::chrono;
            high_resolution_clock::time_point end = high_resolution_clock::now();
            duration dur = duration_cast>(end - __start);
            std::cout << dur.count() << " seconds" << std::endl;
        }
    private:
        std::chrono::high_resolution_clock::time_point __start;
    };
    

    The only thing is needed to do is to create an object in your function at the beginning of that function

    void veryLongExecutingFunction() {
        duration_calculator dc;
        for(int i = 0; i < 100000; ++i) std::cout << "Hello world" << std::endl;
    }
    
    int main() {
        veryLongExecutingFunction();
        return 0;
    }
    

    and that's it. The class can be modified to fit your requirements.

提交回复
热议问题