How to get duration like int milli and float seconds from <chrono>?

I am trying to use a chronological library for timers and durations.

I want to have a Duration frameStart; (from the beginning of the application) and Duration frameDelta; (time between frames)

I need to have a frameDelta length of both milliseconds and floating point seconds.

How do you do this with the new C ++ 11 <chrono> ? I am working on this and searching on Google (information is sparse). The code is very obscured and requires special throws and things, I can’t figure out how to use this library correctly.

+46
c ++ c ++ 11 timer chrono
Jan 18 '13 at 1:56
source share
4 answers

Is this what you are 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 is printed for me:

 6.5e-08s 0ms 
+84
Jan 18 '13 at 2:33
source share

I don't know what “milliseconds and floating seconds” mean, 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'; } 
+9
Jan 18 '13 at 2:15
source share

Guess what you are asking for. I assume a millisecond frame timer, you are looking for something that acts as follows:

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

but uses std::chrono ,

 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.

+5
Mar 07
source share

To AAA style using an explicitly entered initialization identifier

 #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'; } 
+3
Mar 05 '15 at 11:14
source share



All Articles