【问题标题】:How to output time in milliseconds in c++?如何在 C++ 中以毫秒为单位输出时间?
【发布时间】:2018-03-28 22:39:16
【问题描述】:
#include <iostream>
#include <chrono>
#include <time.h>
#include <stdio.h>

using namespace std;
using namesapce chrono;

int main() {
  int f;
  time_t start, end;
  time (&start);
  cin >> f;
  time (&end);
  double dif = difftime (end, start);
  printf ("Elapsed time is %.2lf seconds.", dif );
}

大家好,我目前正在处理 C++ 作业,我基本上需要让用户在 10 秒内输入内容。我设法找出如何以秒为单位计算时间,但我需要以毫秒为单位,因为我必须找出超过 10 秒的毫秒数。我对 C++ 没有那么丰富的经验,非常感谢任何可能有助于引导我走向正确方向的建议。非常感谢

【问题讨论】:

标签: c++ c++11 time clock chrono


【解决方案1】:

类似的东西...

#include <iostream>
#include <chrono>
auto start(std::chrono::high_resolution_clock::now());

// Code...

auto end(std::chrono::high_resolution_clock::now());
auto duration(std::chrono::duration_cast<std::chrono::milliseconds>(end - start));
std::cout << "Duration: " << duration.count() << " ms\n";

【讨论】:

    【解决方案2】:

    在 C++11 和更新的标准版本中:

    #include <chrono>
    using namespace std::chrono;
    
    auto start = high_resolution_clock::now();
      // something to measure
    auto end = high_resolution_clock::now();
    duration<double> diff = end - start; // this is in ticks
    milliseconds d = duration_cast<milliseconds>(diff); // ticks to time
    
    std::cout << diff.count() << "s\n";
    std::cout << d.count() << "ms\n";
    

    在那之前:

    <sys/time.h>
    
    struct timeval tp;
    gettimeofday(&tp, NULL);
    long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
    

    您还可以使用这个简单的 sn-p 代码对您的代码块进行基准测试:

    using namespace std::chrono;
    
    class benchmark {
      public:
      time_point<high_resolution_clock>  t0, t1;
      unsigned int *d;
      benchmark(unsigned int *res) : d(res) { 
                     t0 = high_resolution_clock::now();
      }
      ~benchmark() { t1 = high_resolution_clock::now();
                      milliseconds dur = duration_cast<milliseconds>(t1 - t0);
                      *d = dur.count();
      }
    };
    
    // one way to use it can be :
    #define BENCH(TITLE,CODEBLOCK) \
      unsigned int __time__##__LINE__ = 0;  \
      { benchmark bench(&__time__##__LINE__); \
          CODEBLOCK \
      } \
      printf("%s took %dms\n",(TITLE),__time__##__LINE__);
    
    
    int main(void) {
      BENCH("TITLE",{
        for(int n = 0; n < testcount; n++ )
          int a = n % 3;
      });
      return 0;
    }
    

    【讨论】:

      【解决方案3】:

      以下完整程序显示了如何使用 C++11 中添加的 std::chrono 工具来完成此操作:

      #include <iostream>
      #include <chrono>
      #include <thread>
      
      int main(int argc, char *argv[]) {
          // Check args.
      
          if (argc != 2) {
              std::cerr << "Usage: testprog <sleepTime>" << std::endl;
              return 1;
          }
      
          // Create a millisecond sleep time from argument.
      
          auto sleepTime = strtoul(argv[1], nullptr, 10);
          sleepTime = sleepTime * 1234 + 1000;
          std::cout << "Given '" << argv[1] <<
              "', should sleep for about " << sleepTime <<
              "ms ... " << std::flush;
      
          // Get the start time, then wait for a bit.
      
          auto startTime(std::chrono::high_resolution_clock::now());
      
          std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
      
          // Get end time, work out and print duration.
      
          auto endTime(std::chrono::high_resolution_clock::now());
          auto duration(std::chrono::duration_cast<std::chrono::milliseconds>
              (endTime - startTime));
          std::cout << "that took " << duration.count() << "ms." << std::endl;
      }
      

      使用以下bash 测试命令运行它:

      for i in {0..10} ; do ./testprog $i ; done
      

      为您提供您期望的结果:

      Given '0', should sleep for about 1000ms ... that took 1000ms.
      Given '1', should sleep for about 2234ms ... that took 2235ms.
      Given '2', should sleep for about 3468ms ... that took 3469ms.
      Given '3', should sleep for about 4702ms ... that took 4703ms.
      Given '4', should sleep for about 5936ms ... that took 5937ms.
      Given '5', should sleep for about 7170ms ... that took 7170ms.
      Given '6', should sleep for about 8404ms ... that took 8404ms.
      Given '7', should sleep for about 9638ms ... that took 9638ms.
      Given '8', should sleep for about 10872ms ... that took 10872ms.
      Given '9', should sleep for about 12106ms ... that took 12106ms.
      Given '10', should sleep for about 13340ms ... that took 13340ms.
      

      该代码中的 important 行实际上只是获取开始和结束时间点然后计算出它们之间的持续时间的行。它们可以归结为:

      #include <chrono>
      
      auto startTime(std::chrono::high_resolution_clock::now());
      
      // Do whatever you want to time.
      
      auto endTime(std::chrono::high_resolution_clock::now());
      auto duration(std::chrono::duration_cast<std::chrono::milliseconds>
          (endTime - startTime));
      auto elapsedMs = duration.count();
      

      【讨论】:

        猜你喜欢
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-28
        • 1970-01-01
        • 2011-08-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多