user2204292
user2204292

Reputation: 181

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?

Upvotes: 4

Views: 5311

Answers (3)

Pranshu Gupta
Pranshu Gupta

Reputation: 664

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.

Upvotes: 8

Phil
Phil

Reputation: 1266

I highly recommend you look at Handmade Hero. Casey records creating an entire game in a series of video episodes. In one of the early episodes he discusses determining wall-clock time on windows using QueryPerformanceCounter and QueryPerformanceFrequency

He also discusses using cpu cycle counts although those are useful only assuming a constant processor clock speed.

He talks about these issues again in later episodes: https://hero.handmade.network/episode/game-architecture/day113 and https://hero.handmade.network/episode/game-architecture/day177

Since you are looking for a solution in a game loop, these videos will probably be of interest at least even if you use the cross-platform solution from @Pranshu. You are likely ok for a game using a platform dependent method to get a more accurate clock.

I'll point out that high_resolution_clock provides the highest resolution clock available by the system that the library knows about so it might not be any more accurate than using system_clock or steady_clock. (It uses steady_clock on my OSX box.)

Upvotes: 1

Makaronodentro
Makaronodentro

Reputation: 957

A cross-platform and easy solution would be to use the chrono library

Example:

#include <iostream>
#include <chrono>

void gameFunction()
{
    // start()
    // end()
}

int main()
{
    auto t1 = std::chrono::high_resolution_clock::now();
    gameFunction();
    auto t2 = std::chrono::high_resolution_clock::now();

    auto elapsed_time = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << elapsed_time << std::endl;
    return 0;
}

Finally note that you will need a at least C++11 for this to work, so set the -std= flag to at least c++11. For example:

g++ -std=c++11 game.cpp -o game

Upvotes: 6

Related Questions