C++ Cross-Platform High-Resolution Timer

前端 未结 14 2150
不知归路
不知归路 2020-11-22 12:45

I\'m looking to implement a simple timer mechanism in C++. The code should work in Windows and Linux. The resolution should be as precise as possible (at least millisecond a

14条回答
  •  孤街浪徒
    2020-11-22 13:52

    Matthew Wilson's STLSoft libraries provide several timer types, with congruent interfaces so you can plug-and-play. Amongst the offerings are timers that are low-cost but low-resolution, and ones that are high-resolution but have high-cost. There are also ones for measuring pre-thread times and for measuring per-process times, as well as all that measure elapsed times.

    There's an exhaustive article covering it in Dr. Dobb's from some years ago, although it only covers the Windows ones, those defined in the WinSTL sub-project. STLSoft also provides for UNIX timers in the UNIXSTL sub-project, and you can use the "PlatformSTL" one, which includes the UNIX or Windows one as appropriate, as in:

    #include 
    #include 
    
    int main()
    {
        platformstl::performance_counter c;
    
        c.start();
        for(int i = 0; i < 1000000000; ++i);
        c.stop();
    
        std::cout << "time (s): " << c.get_seconds() << std::endl;
        std::cout << "time (ms): " << c.get_milliseconds() << std::endl;
        std::cout << "time (us): " << c.get_microseconds() << std::endl;
    }
    

    HTH

提交回复
热议问题