在一定时间后停止程序执行的更好方法

better way to stop program execution after certain time

本文关键字:执行 更好 方法 程序 定时间      更新时间:2023-10-16

我有以下命令,在一定时间后停止执行程序。

#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;