Reputation: 5313
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 frameDelta;
( time between frames )
I need to be able to get the frameDelta
duration as milliseconds and float seconds.
How do you do this with the new c++11 <chrono>
libraries? I've been working on it and googling ( information is sparse ). The code is heavily templated and requires special casts and things, I can't figure out how to use this library correctly.
Upvotes: 130
Views: 258674
Reputation: 11
float GetTimeFloat() {
return std::chrono::duration_cast<std::chrono::duration<float, std::milli>>(std::chrono::high_resolution_clock::now().time_since_epoch()).count() / 1000;
}
Upvotes: 1
Reputation: 331
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.
Upvotes: 33
Reputation: 15334
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';
}
Upvotes: 12
Reputation: 219345
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
Upvotes: 209
Reputation: 171433
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';
}
Upvotes: 18