Timer function to provide time in nano seconds using C++

前端 未结 16 2341
野趣味
野趣味 2020-11-22 06:02

I wish to calculate the time it took for an API to return a value. The time taken for such an action is in the space of nano seconds. As the API is a C++ class/function, I a

16条回答
  •  野的像风
    2020-11-22 06:09

    Minimalistic copy&paste-struct + lazy usage

    If the idea is to have a minimalistic struct that you can use for quick tests, then I suggest you just copy and paste anywhere in your C++ file right after the #include's. This is the only instance in which I sacrifice Allman-style formatting.

    You can easily adjust the precision in the first line of the struct. Possible values are: nanoseconds, microseconds, milliseconds, seconds, minutes, or hours.

    #include 
    struct MeasureTime
    {
        using precision = std::chrono::microseconds;
        std::vector times;
        std::chrono::steady_clock::time_point oneLast;
        void p() {
            std::cout << "Mark " 
                    << times.size()/2
                    << ": " 
                    << std::chrono::duration_cast(times.back() - oneLast).count() 
                    << std::endl;
        }
        void m() {
            oneLast = times.back();
            times.push_back(std::chrono::steady_clock::now());
        }
        void t() {
            m();
            p();
            m();
        }
        MeasureTime() {
            times.push_back(std::chrono::steady_clock::now());
        }
    };
    

    Usage

    MeasureTime m; // first time is already in memory
    doFnc1();
    m.t(); // Mark 1: next time, and print difference with previous mark
    doFnc2();
    m.t(); // Mark 2: next time, and print difference with previous mark
    doStuff = doMoreStuff();
    andDoItAgain = doStuff.aoeuaoeu();
    m.t(); // prints 'Mark 3: 123123' etc...
    

    Standard output result

    Mark 1: 123
    Mark 2: 32
    Mark 3: 433234
    

    If you want summary after execution

    If you want the report afterwards, because for example your code in between also writes to standard output. Then add the following function to the struct (just before MeasureTime()):

    void s() { // summary
        int i = 0;
        std::chrono::steady_clock::time_point tprev;
        for(auto tcur : times)
        {
            if(i > 0)
            {
                std::cout << "Mark " << i << ": "
                        << std::chrono::duration_cast(tprev - tcur).count()
                        << std::endl;
            }
            tprev = tcur;
            ++i;
        }
    }
    

    So then you can just use:

    MeasureTime m;
    doFnc1();
    m.m();
    doFnc2();
    m.m();
    doStuff = doMoreStuff();
    andDoItAgain = doStuff.aoeuaoeu();
    m.m();
    m.s();
    

    Which will list all the marks just like before, but then after the other code is executed. Note that you shouldn't use both m.s() and m.t().

提交回复
热议问题