【问题标题】:How to calculate time in c++?如何在 C++ 中计算时间?
【发布时间】:2013-04-06 23:16:12
【问题描述】:

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

【问题讨论】:

  • 这取决于你的事件处理库。 C++ 本身不提供任何事件系统,但在我使用过的任何事件系统中,知道系统时间和日期有助于设置重复事件。
  • 你总是可以创建一个线程,它接受一个函数并循环,休眠三秒钟并调用它。这更概括了它,并允许重用。不过,如果我要这样做,也请花点时间睡觉。
  • 您不只是在寻找sleep 函数吗?创建一个新线程,让它在你休眠 3 秒的地方无限循环并打印 hello。
  • @A4L,或者std::this_thread::sleep_for,这是标准的C++11。
  • 我在考虑使用 difftime 但睡眠会更好,对吧?

标签: c++ time.h


【解决方案1】:

这是一个使用两个线程的示例,因此您的程序不会在 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();
}

【讨论】:

    【解决方案2】:

    您可以使用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
      }
    

    【讨论】:

      【解决方案3】:

      这取决于您的操作系统/编译器。

      案例 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 平台上,您可以简单地使用:
      睡眠(以秒为单位);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-26
        • 2010-09-05
        相关资源
        最近更新 更多