Reputation: 53
I try to get the time elapsed between two points in time in milliseconds as integer or in seconds as double. I'm trying to put constant acceleration of 4m/s² on something. I got this already:
int main() {
double accel = 4, velocity = 0;
auto start = chrono::system_clock::now();
sleep(3);
auto ende = chrono::system_clock::now();
chrono::duration<double> elapsed_seconds = ende - start;
velocity += accel * elapsed_seconds; //This is where I don't know what to put instead of "elapsed_seconds"
cout << "Velocity after " << elapsed_seconds << "s is " << velocity << "m/s" << endl;
return 0;
}
But as you might see it doesn't work. I already found something like
chrono::duration_cast<ms>(elapsed_time);
but I can't get it to work. Do you have any ideas?
Upvotes: 1
Views: 995
Reputation: 3225
To get the seconds as a double:
auto seconds = chrono::duration<double>(ende - start);
auto val = seconds.count();
To get milliseconds:
auto ms = chrono::duration_cast<chrono::milliseconds>(ende - start);
auto val = ms.count();
Be careful when using duration_cast
, you can lose precision.
Upvotes: 2
Reputation: 585
It's maybe a little strange to say you "count" a double but elapsed_seconds.count() will return the underlying value.
Upvotes: 3