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

前端 未结 16 2292
野趣味
野趣味 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:08

    Using Brock Adams's method, with a simple class:

    int get_cpu_ticks()
    {
        LARGE_INTEGER ticks;
        QueryPerformanceFrequency(&ticks);
        return ticks.LowPart;
    }
    
    __int64 get_cpu_clocks()
    {
        struct { int32 low, high; } counter;
    
        __asm cpuid
        __asm push EDX
        __asm rdtsc
        __asm mov counter.low, EAX
        __asm mov counter.high, EDX
        __asm pop EDX
        __asm pop EAX
    
        return *(__int64 *)(&counter);
    }
    
    class cbench
    {
    public:
        cbench(const char *desc_in) 
             : desc(strdup(desc_in)), start(get_cpu_clocks()) { }
        ~cbench()
        {
            printf("%s took: %.4f ms\n", desc, (float)(get_cpu_clocks()-start)/get_cpu_ticks());
            if(desc) free(desc);
        }
    private:
        char *desc;
        __int64 start;
    };
    

    Usage Example:

    int main()
    {
        {
            cbench c("test");
            ... code ...
        }
        return 0;
    }
    

    Result:

    test took: 0.0002 ms

    Has some function call overhead, but should be still more than fast enough :)

提交回复
热议问题