在一定时间后停止程序执行的更好方法
better way to stop program execution after certain time
我有以下命令,在一定时间后停止执行程序。
#include <iostream>
#include<ctime>
using namespace std;
int main( )
{
time_t timer1;
time(&timer1);
time_t timer2;
double second;
while(1)
{
time(&timer2);
second = difftime(timer2,timer1);
//check if timediff is cross 3 seconds
if(second > 3)
{
return 0;
}
}
return 0;
}
如果时间从23:59增加到00:01,以上程序是否有效?
如果还有其他更好的方法吗?
如果你有C++11,你可以看看这个例子:
#include <thread>
#include <chrono>
int main() {
std::this_thread::sleep_for (std::chrono::seconds(3));
return 0;
}
或者,我会选择你选择的线程库,并使用它的线程睡眠功能。在大多数情况下,最好将线程发送到睡眠状态,而不是忙于等待。
time()
返回自大纪元以来的时间(UTC,1970年1月1日00:00:00),以秒为单位测量。因此,一天中的时间并不重要。
您可以在C++11中使用std::chrono::steady_clock
。查看now
静态方法中的示例以获取示例:
using namespace std::chrono;
steady_clock::time_point clock_begin = steady_clock::now();
std::cout << "printing out 1000 stars...n";
for (int i=0; i<1000; ++i) std::cout << "*";
std::cout << std::endl;
steady_clock::time_point clock_end = steady_clock::now();
steady_clock::duration time_span = clock_end - clock_begin;
double nseconds = double(time_span.count()) * steady_clock::period::num / steady_clock::period::den;
std::cout << "It took me " << nseconds << " seconds.";
std::cout << std::endl;
相关文章:
- C++:将控制台输出存储在宏中更好吗
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 初始化具有非默认构造函数的std::数组项的更好方法
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 为什么新的随机库比std::rand()更好
- 寻找一种更好的方法来表示无符号字符数组
- 哪种方法更好,性能明智
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 什么是更好的做法?通过指针或标识符传递类成员?
- 寻求更好地理解标准::访问
- 线程消息传递或更好:在"大师班"中访问其他班级的成员
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 是STD ::系统或执行更好的练习
- 强制执行此模板的更好方法
- 执行调试日志记录的更好方法
- 执行直接指针操作还是 [] 更好
- 在 C++ 中执行此操作的视觉更好方法?标准::字符串
- 除了 setter 和 getter 之外的任何其他方法,它们将执行相同的功能但更好
- 有没有比迭代更好的方法在C++中执行URL模式匹配
- 在一定时间后停止程序执行的更好方法