CUDA 设备中的内存分配不是预期的

Memory allocation in CUDA device is not what is expected

我不能创建新标签,但它应该在 MANAGEDCUDA 标签上,因为我正在使用该框架在 C# 中使用 CUDA。

我用这段代码分配了 2 个 INT 数组用于测试:

Console.WriteLine("Cells: "+sum+" Expected Total Memory (x4): "+sum*4);
int temp= 0;
temp = cntxt.GetFreeDeviceMemorySize();
Console.Write("\n Memory available before:" + cntxt.GetFreeDeviceMemorySize() + "\n");
CudaDeviceVariable<int> matrix = new CudaDeviceVariable<int>(sum);
CudaDeviceVariable<int> matrixDir = new CudaDeviceVariable<int>(sum);
Console.Write("\n Memory available after allocation:" + cntxt.GetFreeDeviceMemorySize() + "\n");
Console.WriteLine("Memory took: "+(temp - cntxt.GetFreeDeviceMemorySize()));
Console.WriteLine("Diference between the expected and allocated: " + ((temp - cntxt.GetFreeDeviceMemorySize())-sum*8));

在 运行 之后,我在控制台中得到了这个:

当您通过分配器(malloccudaMalloc、...)分配内存时,它需要在特殊的元数据结构中跟踪您分配的字节。例如,此元数据可能包含分配的字节数及其在内存中的位置、一些填充以对齐分配以及缓冲区溢出检查。

为了减少管理开销,大多数现代分配器使用,也就是说,它们以固定大小的不可分割的块分配内存。在许多主机系统上,此大小默认为 4 kB。

在您的具体情况下,CUDA 似乎以 64 kB 的页面为您的内存分配请求提供服务。也就是说,如果你请求 56 kB,CUDA 无论如何都会为你提供 64 kB,而未使用的 8 kB 是 "wasted"(从你的应用程序的角度来看)。

当您请求分配 1552516 字节(即 23.7 页)时,运行时将为您提供 24 页(1572864 字节):即额外的 20348 字节。加倍(因为你有 2 个数组),这就是你的 40696 字节差异的来源。

Note: The page size varies between GPUs and driver versions. You may try to find it out experimentally by yourself, or search for results published by other people. In any case, this is (to the best of my knowledge) not documented, and may therefore not be relied upon if you intend your program to be portable.