c++ - std::vector 和动态分配数组有什么区别?

标签 c++

我写了两个函数来比较 std::vector 和动态分配数组的时间成本

#include <iostream>
#include <vector>
#include <chrono>

void A() {
  auto t1 = std::chrono::high_resolution_clock::now();
  std::vector<float> data(5000000);
  auto t2 = std::chrono::high_resolution_clock::now();

  float *p = data.data();
  for (int i = 0; i < 5000000; ++i) {
    p[i] = 0.0f;
  }
  auto t3 = std::chrono::high_resolution_clock::now();
  std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << " us\n";
  std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count() << " us\n";
}

void B() {
  auto t1 = std::chrono::high_resolution_clock::now();
  auto* data = new float [5000000];
  auto t2 = std::chrono::high_resolution_clock::now();
  float *ptr = data;
  for (int i = 0; i < 5000000; ++i) {
    ptr[i] = 0.0f;
  }
  auto t3 = std::chrono::high_resolution_clock::now();
  std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << " us\n";
  std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count() << " us\n";
}

int main(int argc, char** argv) {
  A();
  B();
  return 0;
}

A() 花费了大约 6000 us 来初始化 vector ,然后 1400 us 来填充零。

B() 花费不到 10 us 来分配内存,然后 5800 us 来填充零。

为什么他们的时间成本相差这么大?

编译器:g++=9.3.0

标志:-O3 -DNDEBUG

最佳答案

首先,请注意 std::vector<float>构造函数已经将 vector 归零。

对于您观察到的行为,有许多似是而非的系统级解释:

一个非常合理的是缓存:当你使用new分配数组时,返回指针引用的内存不在缓存中。创建 vector 时,构造函数会将分配的内存区域归零,从而将内存放入缓存。因此,后续清零将命中缓存。

其他原因可能包括编译器优化。编译器可能会意识到您的归零对于 std::vector 是不必要的。不过,鉴于您获得的数字,我会在这里打折扣。

关于c++ - std::vector 和动态分配数组有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71292753/

相关文章:

c++删除指针指针的语句

c++ - 可调整大小和动态二维数组的更好解决方案

c++ - 更改 Windows DLL 加载顺序? (加载顺序,不是搜索顺序)

c++ - 单例对象的 Unresolved external symbol 链接错误

c++ - 如何使用模板将结构存储在指针数组中

c++ - 当 Base 和 Derived 都使用 Derived 类型参数进行模板化时调用 Base 构造函数时出现编译器错误

c++ - 如何在QT中制作二维数组?

c++ - 在 C/C++ 中不可能否定 -2147483648?

c++ - 如何在 Windows 下用 C++ 在远程机器上启动一个进程

c++ - 匿名枚举的使用