user2204292 user2204292 - 1 month ago 17
C++ Question

Keep track of time in a game loop in C++

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?

Answer

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. So, it is pretty much very precise. :) Hope that helps.