gpt4 book ai didi

c++ - C++中如何计算时间?

转载 作者:行者123 更新时间:2023-11-30 01:59:47 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何在 c++ 中计算时间。我在做一个程序,每 3 秒发生一个事件,例如打印出“你好”等;

最佳答案

这是一个使用两个线程的示例,这样您的程序就不会卡住,并且 this_thread::sleep_for() 在 C++11 中:

#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();
}

关于c++ - C++中如何计算时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15857102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com