How can I keep track of time in seconds and milliseconds since my game/program started? I can use the clock()
function but I hear it is not that accurate. Is there a better way?
You can use the chrono library in C++ Here is a code sample:
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
int main() {
high_resolution_clock::time_point t1 = high_resolution_clock::now();
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
cout << time_span.count() << " seconds\n";
return 0;
}
Note that this c++11, so to compile it you should use the flag -std=c++11
$ g++ -std=c++11 test.cpp -o test
This exact piece of code gave 4e-07 seconds on my PC.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With