How to get duration, as int milli's and float seconds from ?

前端 未结 4 1167
甜味超标
甜味超标 2020-12-04 07:54

I\'m trying to use chrono library for timers and durations.

I want to be able to have a Duration frameStart; ( from app start ) and a Duration fra

相关标签:
4条回答
  • 2020-12-04 08:16

    Is this what you're looking for?

    #include <chrono>
    #include <iostream>
    
    int main()
    {
        typedef std::chrono::high_resolution_clock Time;
        typedef std::chrono::milliseconds ms;
        typedef std::chrono::duration<float> fsec;
        auto t0 = Time::now();
        auto t1 = Time::now();
        fsec fs = t1 - t0;
        ms d = std::chrono::duration_cast<ms>(fs);
        std::cout << fs.count() << "s\n";
        std::cout << d.count() << "ms\n";
    }
    

    which for me prints out:

    6.5e-08s
    0ms
    
    0 讨论(0)
  • 2020-12-04 08:23

    Taking a guess at what it is you're asking for. I'm assuming by millisecond frame timer you're looking for something that acts like the following,

    double mticks()
    {
        struct timeval tv;
        gettimeofday(&tv, 0);
        return (double) tv.tv_usec / 1000 + tv.tv_sec * 1000;
    }
    

    but uses std::chrono instead,

    double mticks()
    {
        typedef std::chrono::high_resolution_clock clock;
        typedef std::chrono::duration<float, std::milli> duration;
    
        static clock::time_point start = clock::now();
        duration elapsed = clock::now() - start;
        return elapsed.count();
    }
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-04 08:32

    In AAA style using the explicitly typed initializer idiom:

    #include <chrono>
    #include <iostream>
    
    int main(){
      auto start = std::chrono::high_resolution_clock::now();
      // Code to time here...
      auto end = std::chrono::high_resolution_clock::now();
    
      auto dur = end - start;
      auto i_millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
      auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
      std::cout << i_millis.count() << '\n';
      std::cout << f_secs.count() << '\n';
    }
    
    0 讨论(0)
  • 2020-12-04 08:36

    I don't know what "milliseconds and float seconds" means, but this should give you an idea:

    #include <chrono>
    #include <thread>
    #include <iostream>
    
    int main()
    {
      auto then = std::chrono::system_clock::now();
      std::this_thread::sleep_for(std::chrono::seconds(1));
      auto now = std::chrono::system_clock::now();
      auto dur = now - then;
      typedef std::chrono::duration<float> float_seconds;
      auto secs = std::chrono::duration_cast<float_seconds>(dur);
      std::cout << secs.count() << '\n';
    }
    
    0 讨论(0)
提交回复
热议问题