c++ - 测量剩余使用时间

标签 c++

我想制作一个函数,引用上次函数被调用的时间,以确保最多只能每 10 秒调用一次:

void SetUseFunctionLastTime()
    {
        std::chrono::system_clock::now();
    }

        bool UseFunction()
        {
            if (/*Code here*/) /*HERE: I want to check the remaining time 
                               left before I can call it again*/
            {
                Log("Wait %d seconds to use this", seconds_left)
                return false;
            }

        SetUseFunctionLastTime()
    }

你是如何做到这一点的?

最佳答案

#include <chrono>

bool UseFunction() {
    constexpr std::chrono::duration<double> interval_seconds{ 10.0 };
    static std::chrono::time_point<std::chrono::steady_clock> last_call{ std::chrono::steady_clock::now() };
    const auto now = std::chrono::steady_clock::now();
    const auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(now - last_call);
    const auto seconds_left = std::chrono::duration_cast<std::chrono::seconds>(interval_seconds - elapsed_time).count();
    if (seconds_left > 0) {
        printf("Wait %lld seconds to use this\n", seconds_left);
        return false;
    }
    else {
        last_call = now;
        printf("Returning true.\n");
        return true;
    }
}

关于c++ - 测量剩余使用时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58784252/

相关文章:

c++ - 无法 move std::any

c++ - std::stringstream 中双输出的默认格式标志(和宽度)是什么?

c++ - 是否有一种简单、标准的方法通过分配器访问 "new"和 "delete"对象?

c++ - 后增量运算符如何与用户定义的类型一起使用?

c++ - 来自 boost 文件系统的未解析符号

构造函数中的 C++ 错误

c# - 在来自 c#(回调)的非托管 c++ dll 中使用循环操作

c++ - Unicode 和文本控件未正确转换为 UTF8

C++ -- Detours (Win32 API Hijacking) -- 劫持类方法

c++ - 迭代器类 : compiler error in g++ while doing iterator add or subtract (works in VS2010)