用于处理大数组的虚拟内存示例 [英] Sample of virtual memory using to work with Big Arrays

查看:23
本文介绍了用于处理大数组的虚拟内存示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C++/C# 和 WinAPI 很笨.有人可以与我分享有用的链接或展示使用虚拟内存处理大数组的简单示例(在 C++ 或 C# 上).

I am dumb in C++/C# and WinAPI. Can someone share with me useful links or show simple sample of using virtual memory for working with big arrays( on C++ or on C#).

提前致谢.

推荐答案

虚拟内存不是您的编程语言的属性.您无法永远从C++ 程序或 C# 程序.在任何现代(<20 年)硬件或操作系统上,您肯定没有直接控制它的能力.

Virtual memory is not a property of your programming language. You cannot ever see virtual memory from a C++ program or a C# program. You are certainly not, on any modern (<20 years) hardware or operating system afforded the ability to control it directly.

但你总是,总是使用它.

But you're always, always using it.

在您的本地机器上尝试以下程序:

Try the following program on your local machine:

#include <iostream>
int main(int, const char*[])
{
    const std::size_t one_megabyte = 1024 * 1024;
    char* gigantic_array[5*1024];   // 5GB in blocks of 1MB

    std::size_t counter = 0;
    while (true) {
        // Allocate and use the memory (prevents OS cheating)
        gigantic_array[counter] = new char[one_megabyte];
        for (std::size_t i = 0; i < one_megabyte; ++i)
             gigantic_array[counter][i] = 'F';

        ++counter;
        std::cout << "Allocated " << counter / 1024. << "GB of memory." << std::endl;
    }

    return 0;
}

在运行此程序之前,请在单独的 shell 中运行 top.现在运行它.您将很快看到您刚刚运行的程序在列表中名列前茅.数字将滚动...

Before you run this program, run top in a separate shell. Now run it. You're going to very quickly see the program you just ran race to the top of the list. Numbers will be scrolling by...

现在,您可能会注意到暂停.在我的笔记本电脑上,这或多或少发生在 1.3 GB.在此暂停期间,您的机器上的物理内存已用完,虚拟内存开始将内容交换到磁盘.同样,您不只是打开虚拟内存,而是通过实际将其从 RAM 中逐出,从而增加了工作难度.

Now soon, you'll probably notice a pause. On my laptop, that happened at 1.3 GB, more or less. At this pause, you're out of physical memory on your machine and virtual memory starts swapping things out to disk. Again, you didn't just turn on virtual memory, you only made its job harder by actually making it evict things from RAM.

现在等等.你的机器有多少内存?我这里有 4GB.在分配了 5.5GB 的内存后,我手动杀死了该程序.同样,你永远不会打开它".这是操作系统的一项基本功能,您的程序无法轻易判断它使用了多少物理内存.

Now wait. How much RAM do you have on your machine? I have 4GB here. I killed the program by hand after it had allocated 5.5GB of memory. Again, you never "turn it on". It's a basic function of the operating system that your program can't easily tell how much physical memory it's using.

所以我希望我已经说服你以不同的方式看待虚拟内存.希望这也能帮助您解决大数组问题.

So I hope I've convinced you to look at virtual memory a little differently. Hopefully that helps you get on with your big array problem, as well.

这篇关于用于处理大数组的虚拟内存示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆