我是一个 CUDA 新手,所以想知道是否有人可以帮助我。
我读到固定可以显着提高您的程序性能,因此我正努力做到这一点。我在计算能力为 1.0 的 GeForce GT 330 上运行我的代码。
当我运行我的程序时,我发现 cudaMallocHost 无法分配内存,因此我将我的问题浓缩为一个小示例,如下所示。
网格.hpp
#ifndef MESH_HPP_
#define MESH_HPP_
#include <cstddef>
#include <vector>
#include <driver_types.h>
class Mesh{
public:
Mesh();
~Mesh();
void pin_data();
std::vector<size_t> _a;
size_t* _a_pinned;
private:
void cuda_check(cudaError_t success);
};
#endif /* MESH_HPP_ */
网格.cpp
#include <iostream>
#include <cmath>
#include <vector>
#include <string.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include "Mesh.hpp"
Mesh::Mesh(){
for(size_t i = 0; i < 10; i++){
_a.push_back(i);
}
}
Mesh::~Mesh() {
cudaFreeHost(_a_pinned);
}
void Mesh::pin_data() {
size_t _a_bytes = sizeof(size_t) * _a.size();
cuda_check(cudaMallocHost((void **)_a_pinned, _a_bytes));
memcpy(_a_pinned, &_a[0], _a_bytes);
}
void Mesh::cuda_check(cudaError_t status) {
if (status != cudaSuccess) {
std::cout << "Error could not allocate memory result " << status << std::endl;
exit(1);
}
}
main.cpp
#include <cstdlib>
#include <iostream>
#include "Mesh.hpp"
int main(int argc, char **argv){
Mesh *mesh = new Mesh();
mesh->pin_data();
delete mesh;
return EXIT_SUCCESS;
}
当我运行我的代码时,输出是:
'错误无法分配内存结果11'
最佳答案
改变这一行:
cuda_check(cudaMallocHost((void **)_a_pinned, _a_bytes));
为此:
cuda_check(cudaMallocHost((void **)&_a_pinned, _a_bytes));
(唯一的变化是添加符号)
cudaMalloc 操作期望修改指针值,因此它们 must be passed the address of the pointer to modify ,而不是指针本身。
这对我来说已经解决了。我仍然对 <size_t>
的 vector 感到困惑。但对每个人来说都是他或她自己的。
如果你想,作为一个建议,在你的Mesh:cuda_check
方法,你可以像这样添加一行:
std::cout << "Error could not allocate memory result " << status << std::endl;
std::cout << "Error is: " << cudaGetErrorString(status) << std::endl; //add this line
关于c++ - cudaMallocHost 甚至无法分配最小的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180832/