C++ - 精确时间 vector

标签 c++

我一直在寻找精度高的 C++ 时钟,我找到了 this answer谁使用 std 的 chrono 库。然后我尝试将所有持续时间放在一个 vector 中。我有一些问题。这是一个简单的测试代码:

#include <iostream>
#include <vector>

#include <chrono>

#include <stdlib.h>

int main() {
  int i, j;

  std::chrono::high_resolution_clock::time_point begin;
  std::chrono::high_resolution_clock::time_point end;

//  std::chrono::duration<long int, std::micro> duration;

  std::vector<std::chrono::duration<long int, std::micro> > times;

  for (i=0 ; i<10 ; ++i) {

    begin=std::chrono::high_resolution_clock::now();
    for (j=0 ; j<1000000 ; ++j) {
      // Do things
    }
    end=std::chrono::high_resolution_clock::now();

    auto duration=std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count();

    times.push_back(duration);

  }


  return EXIT_SUCCESS;
}


当我编译时,我得到了这个错误。 Gcc 将该 vector 视为 long int vector ,我不明白为什么。

test.cpp:28:29: erreur: no matching function for call to ‘std::vector<std::chrono::duration<long int, std::ratio<1l, 1000000l> > >::push_back(long int&)’
     times.push_back(duration);


我还尝试在第一个循环之前声明变量 duration,例如 cpp reference example (并且没有自动)。但是,当我尝试为其分配一个值时,出现了这个错误:

test.cpp:26:13: erreur: no match for ‘operator=’ (operand types are ‘std::chrono::duration<long int, std::ratio<1l, 1000000l> >’ and ‘std::chrono::duration<long int, std::ratio<1l, 1000000l> >::rep {aka long int}’)
     duration=std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count();



我的问题:

  • 我该如何声明变量 duration(没有 auto)?
  • 我必须如何声明 times vector ?

最佳答案

你快到了,只需删除 .count()在初始化 duration 的行尾.

  • How do I have to declare the variable duration (without the auto)?
  • How do I have to declare the times vector ?

最易读的形式是类型别名,例如

using Duration = std::chrono::microseconds;

std::vector<Duration> times;

const Duration d = std::chrono::duration_cast<Duration>(end - begin);

times.push_back(d);

请注意,我删除了显式表示模板参数 long int .默认帮助类型 <chrono>提供(此处为 std::chrono::microseconds )很好。

关于C++ - 精确时间 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56424171/

相关文章:

c++ - 运算符重载枚举类

C++ Hello World 体系结构的 undefined symbol x86_64 :

C++:带大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?

c++ - 避免频繁加锁

c++ - 用于 cout 顺序的 OpenMP 并行

c++ - 正确删除 с++ 中的类

c++ - 为什么我的继承方法输出基类的成员而不是派生类的成员

c++ - 无法从 glGetShaderInfoLog 检索错误消息

c++ - 指向不完整类型的指针

C++ 运算符和参数