user11308226
user11308226

Reputation:

how to convert int to chrono milliseconds

I have a variable which is of type milliseconds and i want to set it equal to an equation. Here is what ive done so far. It compiles and runs but when it hits this line it stops entering the if statement below.

time = duration<int>(750-(lvl*50));

another thing to note is that i do have an if statement which may also be part of the issue that i'm comparing different data types. here is that if statement:

if(time_since_last >= time) {

the time since last variable is the difference in time of different 2 high_resolution_clock::now()

Upvotes: 13

Views: 21464

Answers (3)

Peter Mears
Peter Mears

Reputation: 1

#include <chrono>
...
milliseconds time = (750ms-(lvl*50ms));

I am assuming you were controlling some delay (time) with an integer (lvl)

Upvotes: -1

ObliteratedJillo
ObliteratedJillo

Reputation: 5166

You can try something like this. For converting an integer value to chrono in milliseconds use std::chrono::milliseconds(value);

auto old_time = std::chrono::high_resolution_clock::now();
this_thread::sleep_for(chrono::milliseconds(500));
auto new_time = std::chrono::high_resolution_clock::now();
auto time_since_last = std::chrono::duration_cast<chrono::milliseconds>(new_time - old_time);   
cout << time_since_last.count();

int value = 1000;
auto time = std::chrono::milliseconds(value);
cout << "   " <<time.count();

if (time_since_last >= time) {
    /* do something */
}

Upvotes: 19

lenik
lenik

Reputation: 23556

You should not use intervals in comparison. Use the absolute values instead. For example:

next_time = curr_time + duration<int>( ... etc ... );
if( time > next_time ) {
    // do something
}

Upvotes: 0

Related Questions