简体   繁体   English

CUDA 通过数组偏移量从设备内存复制单个元素是否安全?

[英]CUDA is it safe to copy a single element from device memory by array offset?

int main()
{
    int n = 1000;
    float *d_a;
    cudaMalloc(&d_a, n * sizeof(float));

    // do something that gives d_a value;
    int index = rand() % n; // copy index
    float res;
    cudaMemcpy(&res, &d_a[index], sizeof(float), cudaMemcpyDeviceToHost);
    cudaMemcpy(&res, d_a + index, sizeof(float), cudaMemcpyDeviceToHost);
    // Are the above 2 the same and legal ?
    cout << res << "\n";
}
return 0;

So I have the following problem.所以我有以下问题。 I need to copy exactly 1 element (random index) from the device array.我需要从设备数组中精确复制 1 个元素(随机索引)。 I don't want to copy the entire array because it'd be wasteful.我不想复制整个数组,因为它会很浪费。

So, is the above methods safe and conform to CUDA programming guide?那么,上述方法是否安全并符合CUDA编程指南?

Yes, there is no problem with what you have shown.是的,您展示的内容没有问题。 It is legal and should copy the element you desire from device to host.这是合法的,应该将您想要的元素从设备复制到主机。

Regarding your two methods, they are the same (this is a C++ question, not specific to CUDA).关于您的两种方法,它们是相同的(这是一个 C++ 问题,并非特定于 CUDA)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM