如何在c++中计算时间

How to calculate time in c++?

本文关键字:计算 时间 c++      更新时间:2023-10-16

我想弄清楚如何在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平台上,您可以简单地使用:
睡眠(以秒为单位);