본문 바로가기

C/C++

[c++14] 함수 실행 시간 측정

함수 실행 시간 측정을 하려면,

실행 전 시간을 체크하고, 실행 후 시간을 체크해서 차이를 계산해주어야 한다.

그러나, 아래 템플릿을 이용해서 쉽게 할수 있다.




template<typename F, typename ...Args>

static auto duration(F&& func, Args&&... args)

{

        using namespace std::chrono;

        auto start = steady_clock::now();

 

        auto ret = std::forward<decltype(func)>(func)(std::forward<Args>(args)...);

 

        auto dur = duration_cast<milliseconds>(steady_clock::now() - start);

        TRACE(_T("dur : %d\n"), dur.count());

        return ret;

}



사용은 대충 이렇게..

#include <thread>

int func(int ms) {

        std::this_thread::sleep_for(std::chrono::milliseconds(ms));

        return 10;

}

 


duration(func, 1000);





그리고,. Effective Modern C++에서 나온 람다를 이용하면 아래와 같이 할수 있다.


auto timeFuncInvocation =

[](auto&& func, auto&&... params)

{

        auto start = GetTickCount();

        auto ret = std::forward<decltype(func)>(func) (

               std::forward<decltype(params)>(params)...);

 

        TRACE(_T(">> %d\n"), GetTickCount() - start);

        return ret;

};


<출처>

http://stackoverflow.com/questions/2808398/easily-measure-elapsed-time