2014-04-08 48 views
0

我有以下几点,在某些时间后停止执行程序。更好的方法在特定时间后停止程序执行

#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,上面的程序会工作吗?

如果还有其他更好的方法?

回答

1

time()返回自Epoch(1970年1月1日UTC,00:00:00)以秒为单位测量的时间。因此,一天的时间并不重要。

+0

,因为我得到的while循环'时间(定时器2)时间;'的内存分配给'timer2'由系统本身释放? – EmptyData

+0

是的,'main()'返回后。 – timrau

2

只要你有C++ 11,你可以看看this example:

#include <thread> 
#include <chrono> 
int main() { 
    std::this_thread::sleep_for (std::chrono::seconds(3)); 
    return 0; 
} 

或者我会与您所选择的线程库去使用它的线程睡眠功能。在大多数情况下,最好是让你的线程进入睡眠状态,而不是忙于等待。

1

您可以在C++ 11中使用std::chrono::steady_clock。检查在now static method的例子为例:

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; 
相关问题