如何在c++中计算时间
How to calculate time in c++?
我想弄清楚如何在c++中计算时间。我正在做一个程序,其中每3秒发生一个事件,例如打印出"hello"等;
这里有一个使用两个线程的例子,这样你的程序就不会冻结,并且在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
}
这取决于你的操作系统/编译器。
案例1:如果你有c++ 11,那么你可以按照Chris的建议使用:
std::this_thread::sleep_for()//你必须包含头文件thread
案例2:
如果你使用的是windows平台,那么你也可以使用如下命令:
#include windows.h
int main ()
{
event 1;
Sleep(1000); // number is in milliseconds 1Sec = 1000 MiliSeconds
event 2;
return 0;
}
案例3:
在linux平台上,您可以简单地使用:
睡眠(以秒为单位);
相关文章:
- 如何计算Big-O表示法中的平均渐近运行时间
- 通过字符串来计算长度需要更长的时间,而不是移动字符串几次?
- 如何计算此排序函数的时间复杂度?
- 计算两个代码块的时间复杂度
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 如何计算函数的时间复杂度?
- 标准::映射::合并的计算时间复杂度
- 以小于一毫秒的精度计算时间的功能
- 更好地线程化代码以减少计算时间的方法
- 像儒略数字用于计算日期一样,是否有任何特定的数字来计算时间
- C++ctime.h将无法正确计算时间
- c++/Qt—计算时间
- 计算时间增量最快的linux C时间函数是什么?看到clock_gettime和gettimeofday表现不佳
- c++ Boost:以毫秒计算时间
- 使用chrono c++库计算时间戳的差异
- 编译后,如何使其显示计算时间?
- 如何在c++中计算时间
- 使用mktime计算时间不正确,以获得UTC+8
- 用c++计算时间
- Boost多边形库布尔函数计算时间