time - Comparison of Duration/Seconds in C++ using chrono doesnt work as supposed? -
edit: works fine, messed in place of code.
i trying increase integer once every minute, using c++11 chrono library. reasons, comparison not work should: returns true every time. wrong cast seconds? shouldn't result int, containing difference of both time points in seconds?
would appreciate help! here's code:
std::chrono::time_point<std::chrono::system_clock> starttime = std::chrono::system_clock::now(); int timeline = 0; int main() { while (true) { std::chrono::time_point<std::chrono::system_clock> = std::chrono::system_clock::now(); int seconds = timeline * 60; if ((std::chrono::duration_cast<std::chrono::seconds>(starttime - now)).count() + seconds <= 0) { timeline++; nextconstellation(); cout << "timeline: " << timeline << endl; } } }
here safer, , more readable way write code:
std::chrono::time_point<std::chrono::system_clock> starttime = std::chrono::system_clock::now(); int timeline = 0; int main() { while (true) { std::chrono::time_point<std::chrono::system_clock> = std::chrono::system_clock::now(); std::chrono::seconds seconds = timeline * std::chrono::minutes{1}; if (starttime - + seconds <= std::chrono::seconds{0}) { timeline++; nextconstellation(); std::cout << "timeline: " << timeline << std::endl; } } } in nutshell, stay within chrono-type system, , trust units conversions you, implicitly wherever possible.
or perhaps more simply:
// ... auto timelimit = timeline * std::chrono::minutes{1}; if (now - starttime >= timelimit) { // ... and if in c++14, add using namespace std::chrono_literals and:
auto timelimit = timeline * 1min;
Comments
Post a Comment