samedi 26 mai 2018

How do I increase a value per second?

I've done some research but couldn't find a way to do it. All solutions I've seen offers only to calculate how much time passed during the execution of the code.

const auto start = std::chrono::high_resolution_clock::now();
// your code
const auto end = std::chrono::high_resolution_clock::now();
const auto elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();

I've thought maybe I can create a value and keep adding elapsed_seconds as milliseconds to it, with modulo I can check if it's above 1000 and if elapsed_seconds % 1000 == 0, I can increase the value.

I failed to do it however. Here is my code:

long long total_time_passed = 0;

int main(int argc, char* argv[])
{
    while (true)
    {
        // some code
        const auto start = std::chrono::high_resolution_clock::now();
        // some code
        const auto end = std::chrono::high_resolution_clock::now();
        const auto elapsed_seconds = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
        total_time_passed += elapsed_seconds;
        cout << "TTPass: " << total_time_passed << "\n";
    }
}

Always prints:

TTPass: 0

How do I make it so TTPass increases by 1 in real time as 1 second passes.

Expected output (per second):

TTPass: 1
TTPass: 2
TTPass: 3
...

I don't want to use sleep(1000). I'm aware of it but it blocks code execution.

If it helps, I'm using Windows 10 with Visual Studio 2017.

Thank you.

Aucun commentaire:

Enregistrer un commentaire