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

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

    What others have posted about running the function repeatedly in a loop is correct.

    For Linux (and BSD) you want to use clock_gettime().

    #include 
    
    int main()
    {
       timespec ts;
       // clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
       clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
    }
    

    For windows you want to use the QueryPerformanceCounter. And here is more on QPC

    Apparently there is a known issue with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a problem. See the second post by sebbbi, where he states:

    QueryPerformanceCounter() and QueryPerformanceFrequency() offer a bit better resolution, but have different issues. For example in Windows XP, all AMD Athlon X2 dual core CPUs return the PC of either of the cores "randomly" (the PC sometimes jumps a bit backwards), unless you specially install AMD dual core driver package to fix the issue. We haven't noticed any other dual+ core CPUs having similar issues (p4 dual, p4 ht, core2 dual, core2 quad, phenom quad).

    EDIT 2013/07/16:

    It looks like there is some controversy on the efficacy of QPC under certain circumstances as stated in http://msdn.microsoft.com/en-us/library/windows/desktop/ee417693(v=vs.85).aspx

    ...While QueryPerformanceCounter and QueryPerformanceFrequency typically adjust for multiple processors, bugs in the BIOS or drivers may result in these routines returning different values as the thread moves from one processor to another...

    However this StackOverflow answer https://stackoverflow.com/a/4588605/34329 states that QPC should work fine on any MS OS after Win XP service pack 2.

    This article shows that Windows 7 can determine if the processor(s) have an invariant TSC and falls back to an external timer if they don't. http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html Synchronizing across processors is still an issue.

    Other fine reading related to timers:

    • https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks
    • http://lwn.net/Articles/209101/
    • http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html
    • QueryPerformanceCounter Status?

    See the comments for more details.

提交回复
热议问题