【问题标题】:Comparison of Duration/Seconds in C++ using chrono doesnt work as supposed?使用 chrono 比较 C++ 中的持续时间/秒数不能按预期工作?
【发布时间】:2017-04-07 18:51:22
【问题描述】:

编辑:工作得很好,我在代码的另一个地方搞砸了。

我正在尝试使用 C++11 chrono 库每分钟增加一次整数。由于某些原因,比较不能正常工作:它只是每次都返回 true。投到秒有什么问题吗?结果不应该是一个int,包含两个时间点的秒差吗?

非常感谢您的帮助!这是代码:

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> now = 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;

        }
    }
}

【问题讨论】:

  • This doesn't even compile。如果我通过将&lt;std::chrono::system_clock&gt; 添加到time_points 来修复它,它会按预期工作。
  • 非常抱歉,在我的代码中的另一个地方做了定义,忘记复制 <:chrono::system_clock> 编辑我的帖子。感谢您告诉我它对您有用,但仍然无法弄清楚为什么它不适合我。
  • 按预期工作,你能给我们nextConstellation()吗?
  • 好的,抱歉打扰了,我的代码结构搞砸了,跳过了 starttime 的初始化。正如 Gill Bates 所说并证实的那样,上述工作有效。感谢您的努力!
  • 我建议在这种情况下删除您的问题。

标签: c++ time chrono seconds


【解决方案1】:

这是编写此代码的更安全、更易读的方法:

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> now = std::chrono::system_clock::now();

        std::chrono::seconds seconds = timeLine * std::chrono::minutes{1};

        if (starttime - now + seconds <= std::chrono::seconds{0}) {
            timeLine++;
            nextConstellation();
            std::cout << "Timeline: " << timeLine << std::endl;

        }
    }
}

简而言之,留在计时类型系统中,并相信它会尽可能隐含地为您进行单位转换。

或者更简单:

    // ...
    auto timelimit = timeLine * std::chrono::minutes{1};

    if (now  - starttime >= timelimit) {
    // ...

如果在 C++14 中,添加 using namespace std::chrono_literals 和:

    auto timelimit = timeLine * 1min;

【讨论】:

    猜你喜欢
    • 2010-12-19
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多