gpt4 book ai didi

c - 如何高效处理大型数组中未使用的部分: virtual memory or manually?

转载 作者:行者123 更新时间:2023-11-30 17:24:50 27 4
gpt4 key购买 nike

考虑以下代码段:

static int const MAX = 1024; // limit on the number of directory entries
int actual = 0; // counter of directory entires
int ptrsize = sizeof(char*);
int i = 0;

char cwd[1024];
DIR* d;
struct dirent** buffer;
struct dirent** file;

getcwd ( cwd, sizeof ( cwd ) );
d = opendir ( cwd );
buffer = (struct dirent**)malloc(MAX * ptrsize); // allocate the large buffer

/* fill the buffer with dirents for each file in the cwd */
while ( ( buffer[actual] = readdir ( d ) ) != NULL ) actual++;

/* copy the active part of the buffer to the file array and free the buffer */
file = (struct dirent**)malloc(actual * ptrsize);
while ( i < actual ) {
file[i] = buffer[i];
i++;
}
free ( buffer );

使用自动虚拟内存,通过以下方式获得相同的结果会更有效吗?

static int const MAX = 1024; // limit on the number of directory entries
int actual = 0; // counter of directory entires

char cwd[1024];
DIR* d;
struct dirent* file[MAX];

getcwd ( cwd, sizeof ( cwd ) );
d = opendir ( cwd );

while ( ( file[actual] = readdir ( d ) ) != NULL ) actual++;

如果目录中有10个文件,则文件的1014个数组元素将不会被使用,所以接近100%。由于虚拟内存会回收空数组元素用于其他目的,它还会更有效吗?

最佳答案

我会让你用我给你的有关内存的信息回答你自己的问题:

内存由不同的部分组成,这里讨论其中的两个部分:计算机给出的部分(映射区域,如您的 char cwd[1024] )和您可以归因的部分(未映射区域,如您的 struct dirent** file; ),所有这些内存都押在“头上”。

程序的最大内存在启动时分配。但它们有两种程序:基础程序和管理员程序。当第二个可以通过添加或抑制一些内存来修改头部时,第一个只能减少最大内存。因此,如果您有大量数据(或少量可用内存),那么当您可以分配 1 次内存时,很难进行 2 次内存分配。

理解 malloc 的一个很好的练习是尝试创建自己的 malloc。这里有一个帮助:http://www.inf.udec.cl/~leo/Malloc_tutorial.pdf

而且,就我而言,如果我可以避免使用 malloc,我就不会使用它,因此我不太担心内存泄漏。但是,这取决于每个人。

关于c - 如何高效处理大型数组中未使用的部分: virtual memory or manually?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27179870/

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