我想制作一个函数,引用上次函数被调用的时间,以确保最多只能每 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/