如何在c ++中输出以毫秒为单位的时间?

Mat*_*att 2 c++ time clock c++11 c++-chrono

#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 );
}
Run Code Online (Sandbox Code Playgroud)

大家好,我目前正在进行C++任务,基本上我需要在10秒内让用户输入内容.我设法找出如何计算秒的时间,但我需要它是毫秒,因为我必须找出10秒以上的毫秒数.我不熟悉C++,并且非常感谢任何可能有助于引导我朝着正确方向前进的建议.非常感谢

can*_*ust 5

沿着这些方向......

#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";
Run Code Online (Sandbox Code Playgroud)


nul*_*ube 5

在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";
Run Code Online (Sandbox Code Playgroud)

在此之前:

<sys/time.h>

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
Run Code Online (Sandbox Code Playgroud)

您还可以使用此简单代码段代码来对代码块进行基准测试:

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;
}
Run Code Online (Sandbox Code Playgroud)