gpt4 book ai didi

c++ - 使用 std::vector 的指数内存消耗增长

转载 作者:太空狗 更新时间:2023-10-29 23:25:25 26 4
gpt4 key购买 nike

我正在开发一个需要提高内存效率的程序。我在我的程序中使用了 std::vector 来存储大量元素。 But, I noticed that the program's memory size grows exponentially when the number of elements are chosen large.比如我写了下面的代码:

#include <iostream>
#include <vector>
using namespace std;

int main(){
int vecSize;
cin >> vecSize;
vector<double> a(vecSize);
return 0;
}

然后我使用 gnu time 命令监控内存消耗,如下所示:

/usr/bin/time -f "Mem: %M" a.out

这是我针对不同 vector 大小得到的内存结果:

VecSize       MemUsage
10: 4720 KB
100: 4720 KB
1000: 4736 KB
10000: 5024 KB
100000: 7744 KB
1000000: 35872 KB
10000000: 317120 KB

Does anybody know why the memory usage is growing so much fast when the number of elements are chosen more than 100000?

最佳答案

MSalters 是对的,我看不懂!

答案很简单。对我来说,增长似乎是线性的。

您选择了呈指数增长的 VecSize。您应该期望 MemUsage 也呈指数增长! (在大 n 的限制下——可能存在小尺寸优化,小 n 的近乎恒定的使用证明了这一点……)

出于好奇,我对数据进行了线性回归,相关系数为 1.0——表明 VecSize 和 MemUsage 之间的关系(如发布的那样)是(很可能......不要杀了我统计学家)线性.

Regression! :)

关于c++ - 使用 std::vector 的指数内存消耗增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27223969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com