C++ 在特定时间后停止程序执行的更好方法
我有以下命令,在一定时间后停止程序的执行C++ 在特定时间后停止程序执行的更好方法,c++,time,C++,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
#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;
}
#包括
#包括
使用名称空间std;
int main()
{
时间计时器1;
时间(&timer1);
时间2;
双秒;
而(1)
{
时间(&timer2);
秒=difftime(timer2,timer1);
//检查timediff是否超过3秒
如果(秒>3)
{
返回0;
}
}
返回0;
}
如果时间从23:59增加到00:01,上述程序是否有效
如果还有其他更好的方法?
time()
返回从纪元(UTC,1970年1月1日,00:00:00)开始的时间,以秒为单位。因此,一天中的时间并不重要。time()
返回从纪元(UTC,1970年1月1日,00:00:00)开始的时间,以秒为单位。因此,一天中的时间并不重要。如果您有C++11,您可以查看
#包括
#包括
int main(){
std::this_thread::sleep_for(std::chrono::seconds(3));
返回0;
}
或者,我会选择一个线程库,并使用它的线程睡眠功能。在大多数情况下,最好将线程发送到睡眠状态,而不是忙于等待。如果您有C++11,您可以查看
#包括
#包括
int main(){
std::this_thread::sleep_for(std::chrono::seconds(3));
返回0;
}
或者,我会选择一个线程库,并使用它的线程睡眠功能。在大多数情况下,最好将线程发送到睡眠状态,而不是忙于等待。您可以在C++11中使用。查看中的示例以获取示例:
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;
使用名称空间std::chrono;
稳定时钟::时间点时钟\u开始=稳定时钟::现在();
std::cout可以在C++11中使用。查看中的示例以获取示例:
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;
使用名称空间std::chrono;
稳定时钟::时间点时钟\u开始=稳定时钟::现在();
std::cout as I在while循环中获取时间time(&timer2)代码>系统本身是否释放了分配给timer2
的内存?是的,在main()
返回后。当我在while循环中获取时间时时间(&timer2)代码>系统本身是否释放了分配给timer2
的内存?是,在main()返回后。