检查已过去 10 分钟
Check was 10 mins elapsed
在我的函数中,我需要检查自上次执行以来经过了多少时间,它是否大于 10 分钟。允许执行。解决这个问题最简单的方法是什么?
clock_t lastExecution ;
boolean isItTime()
{
// ??
}
void doJob()
{
if (isItTime())
{
//Do what I need
lastExecution = clock();
}
}
在MSVC++上clock() returns经过的时间(挂钟,不是CPU消耗的时间),所以clock()
的解决方案可以使用CLOCKS_PER_SEC
宏。
boolean isItTime()
{
return (clock()-lastExecution) >= 10*60*CLOCKS_PER_SEC;
}
但是,CppReference says that std::clock
must return the CPU time consumed, not wall clock time passed. So it seems to do on Linux,因此如果您想检查挂钟时间而不是 CPU 时间,Linux 的解决方案应该不同。
所以跨平台的 C++ 解决方案可以使用 std::chrono :
std::chrono::time_point<std::chrono::system_clock> lastExecution
= std::chrono::system_clock::now();
bool isItTime()
{
std::chrono::duration<double> elapsedSeconds =
std::chrono::system_clock::now() - lastExecution;
return elapsedSeconds.count() >= /* 10 minutes */ 10 * 60;
}
void doJob()
{
if (isItTime())
{
//Do what I need
lastExecution = std::chrono::system_clock::now()
}
}
仍有细微差别需要注意,例如您可能更喜欢 std::chrono::steady_clock 以防您希望物理时间过去 10 分钟,这样 isItTime()
就不会 return true
以防用户将时钟提前 10 分钟,或者系统开始夏令时,或者系统在与互联网时间同步时提前更新时间。
使用现代 C++,阅读变得更容易恕我直言:
#include <chrono>
void f() {
using namespace ::std::chrono;
static auto last_run = steady_clock::now();
if(steady_clock::now() - last_run >= 10min) {
// well, this was easy!
}
last_run = steady_clock::now();
}
注意不是线程安全的,"probably"不会在初始运行时进入>= 10min
条件。
此外,steady_clock
用于确保诸如夏令时开始或结束之类的有趣效果不会破坏您对持续时间的概念(例如夏令时开始前 1 秒之间的持续时间)之后的 1 秒应该是 2 秒,而不是 1 小时 2 秒)
在我的函数中,我需要检查自上次执行以来经过了多少时间,它是否大于 10 分钟。允许执行。解决这个问题最简单的方法是什么?
clock_t lastExecution ;
boolean isItTime()
{
// ??
}
void doJob()
{
if (isItTime())
{
//Do what I need
lastExecution = clock();
}
}
在MSVC++上clock() returns经过的时间(挂钟,不是CPU消耗的时间),所以clock()
的解决方案可以使用CLOCKS_PER_SEC
宏。
boolean isItTime()
{
return (clock()-lastExecution) >= 10*60*CLOCKS_PER_SEC;
}
但是,CppReference says that std::clock
must return the CPU time consumed, not wall clock time passed. So it seems to do on Linux,因此如果您想检查挂钟时间而不是 CPU 时间,Linux 的解决方案应该不同。
所以跨平台的 C++ 解决方案可以使用 std::chrono :
std::chrono::time_point<std::chrono::system_clock> lastExecution
= std::chrono::system_clock::now();
bool isItTime()
{
std::chrono::duration<double> elapsedSeconds =
std::chrono::system_clock::now() - lastExecution;
return elapsedSeconds.count() >= /* 10 minutes */ 10 * 60;
}
void doJob()
{
if (isItTime())
{
//Do what I need
lastExecution = std::chrono::system_clock::now()
}
}
仍有细微差别需要注意,例如您可能更喜欢 std::chrono::steady_clock 以防您希望物理时间过去 10 分钟,这样 isItTime()
就不会 return true
以防用户将时钟提前 10 分钟,或者系统开始夏令时,或者系统在与互联网时间同步时提前更新时间。
使用现代 C++,阅读变得更容易恕我直言:
#include <chrono>
void f() {
using namespace ::std::chrono;
static auto last_run = steady_clock::now();
if(steady_clock::now() - last_run >= 10min) {
// well, this was easy!
}
last_run = steady_clock::now();
}
注意不是线程安全的,"probably"不会在初始运行时进入>= 10min
条件。
此外,steady_clock
用于确保诸如夏令时开始或结束之类的有趣效果不会破坏您对持续时间的概念(例如夏令时开始前 1 秒之间的持续时间)之后的 1 秒应该是 2 秒,而不是 1 小时 2 秒)