[英]How to calculate time in c++?
我想弄清楚如何用c ++計算時間。 我正在制作一個程序,每3秒發生一次事件,例如打印出“你好”等;
這是一個使用兩個線程的示例,因此您的程序不會凍結,而C ++ 11中的this_thread::sleep_for()
:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
void hello()
{
while(1)
{
cout << "Hello" << endl;
chrono::milliseconds duration( 3000 );
this_thread::sleep_for( duration );
}
}
int main()
{
//start the hello thread
thread help1(hello);
//do other stuff in the main thread
for(int i=0; i <10; i++)
{
cout << "Hello2" << endl;
chrono::milliseconds duration( 3000 );
this_thread::sleep_for( duration );
}
//wait for the other thread to finish in this case wait forever(while(1))
help1.join();
}
你可以使用boost::timer
來計算C ++中的時間:
using boost::timer::cpu_timer;
using boost::timer::cpu_times;
using boost::timer::nanosecond_type;
...
nanosecond_type const three_seconds(3 * 1000000000LL);
cpu_timer timer;
cpu_times const elapsed_times(timer.elapsed());
nanosecond_type const elapsed(elapsed_times.system + elapsed_times.user);
if (elapsed >= three_seconds)
{
//more then 3 seconds elapsed
}
它取決於您的OS /編譯器。
情況1:
如果您有C ++ 11,那么您可以按照Chris的建議使用:
std :: this_thread :: sleep_for()//你必須包含頭文件線程
案例2:
如果您使用的是Windows平台,那么您還可以使用以下內容:
#include windows.h
int main ()
{
event 1;
Sleep(1000); // number is in milliseconds 1Sec = 1000 MiliSeconds
event 2;
return 0;
}
案例3:
在linux平台上,您可以簡單地使用:
睡覺(幾秒鍾);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.