C++ Cross-Platform High-Resolution Timer

前端 未结 14 2143
不知归路
不知归路 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 <platformstl/performance/performance_counter.hpp>
    #include <iostream>
    
    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

    0 讨论(0)
  • 2020-11-22 13:52

    I have seen this implemented a few times as closed-source in-house solutions .... which all resorted to #ifdef solutions around native Windows hi-res timers on the one hand and Linux kernel timers using struct timeval (see man timeradd) on the other hand.

    You can abstract this and a few Open Source projects have done it -- the last one I looked at was the CoinOR class CoinTimer but there are surely more of them.

    0 讨论(0)
提交回复
热议问题