C++如何从RAM中解开未使用的全球阵列?

发布于 2025-02-07 20:48:06 字数 279 浏览 1 评论 0原文

在C ++中,当您声明一个大数组时,例如500MB,它不会立即映射到RAM,因为它尚未使用。一旦我第一次访问阵列的页面,它就会映射到物理内存。现在,系统知道我正在使用该页面,但是我如何告诉系统我不再使用某个页面,并且可以按照其意愿将其拆除?

就我而言,我只需要偶尔,所以并非所有时间都需要填充一个大数组,然后在快速随机访问中进行操作。现在我可以每次都使用Malloc,但是为什么要这样做呢?有多种方法可以告诉系统您不需要某个页面,但是它们既可以将其从物理空间虚拟空间删除。我只想将其从物理空间中解开。不可能吗?

In C++ when you declare a big array, say 500MB, it doesn't get mapped to RAM immediately because it is not used yet. As soon as I access a page from the array for the first time, it gets mapped to physical memory. Now the system knows that I am using that page, but how do I tell the system that I am not using some page anymore and that it can unmap it at its will?

In my case I just need to occasionally, so not all the time, fill a big array and operate on it with fast random access. Now I could use malloc every time, but why would I do that? There are ways to tell the system that you don't need some page, but they all both unmap it from physical space and virtual space. I just want to unmap it from physical space. Is it not possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白色秋天 2025-02-14 20:48:06

您无需做任何特别的事情。

内存管理单位会根据需要自动将虚拟内存页面移入物理RAM。如果一段时间没有使用页面,并且需要其他内容的内存,则将其分类。物理RAM包含最近使用的页面,如果由文件支持(例如程序的文本段),或者将其写入磁盘的交换区域然后被驱逐出境,则较旧的页面被驱逐出境。

完成整个数组后,应使用delete []对其进行处理。根据内存分配器的设计,可能也可能不会从虚拟内存中删除内存页面,但是您对此没有任何直接控制。

如果您谈论的是静态阵列,则无法表明您已经完成了它。如果需要执行此操作,则必须使用new动态分配数组,以便delete it。

You don't need to do anything special.

Memory management units automatically move virtual memory pages in and out of physical RAM as needed. If a page hasn't been used in a while, and its memory is needed for something else, it will be paged out. Physical RAM holds the pages that have been used most recently, older pages are just evicted if they're backed by a file (e.g. the text segment of programs), or they're written to the swap area of disk and then evicted.

When you're done with the entire array you should deallocate it with delete[]. Depending on the design of the memory allocator this may or may not remove the memory pages from your virtual memory, but you don't have any direct control over that.

If you're talking about a static array, there's no way to indicate that you're done with it. If you need to do that, the array must be allocated dynamically with new so you can delete it.

往昔成烟 2025-02-14 20:48:06

After a lot of research, luckily, I found another post, where it is exposed that using mmap() with MAP_ANON|MAP_SHARED option to allocate the array and madvise() with MADV_REMOVE option does the trick. You can check the man-pages for details.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文