【发布时间】:2017-03-22 23:49:43
【问题描述】:
在 CUDA 文档中,我发现 cudaDeviceGetAttribute 是一个 __host__ __device__ 函数。所以我想我可以在我的__global__ 函数中调用它来获取我设备的一些属性。可悲的是,这似乎意味着不同的东西,因为如果我将它放入 __device__ 函数并从我的全局调用它,我会收到一个编译错误事件。
是否可以在我的 GPU 上调用 cudaDeviceGetAttribute?或者__host__ __device__ 是什么意思?
这是我的源代码:
__device__ void GetAttributes(int* unique)
{
cudaDeviceAttr attr = cudaDevAttrMaxThreadsPerBlock;
cudaDeviceGetAttribute(unique, attr, 0);
}
__global__ void ClockTest(int* a, int* b, long* return_time, int* unique)
{
clock_t start = clock();
//some complex calculations
*a = *a + *b;
*b = *a + *a;
GetAttributes(unique);
*a = *a + *b - *a;
clock_t end = clock();
*return_time = end - start;
}
int main()
{
int a = 2;
int b = 3;
long time = 0;
int uni;
int* dev_a;
int* dev_b;
long* dev_time;
int* unique;
for (int i = 0; i < 10; ++i) {
cudaMalloc(&dev_a, sizeof(int));
cudaMalloc(&dev_b, sizeof(int));
cudaMalloc(&dev_time, sizeof(long));
cudaMalloc(&unique, sizeof(int));
cudaMemcpy(dev_a, &a, sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(dev_b, &b, sizeof(int), cudaMemcpyHostToDevice);
ClockTest <<<1,1>>>(dev_a, dev_b, dev_time, unique);
cudaMemcpy(&a, dev_a, sizeof(int), cudaMemcpyDeviceToHost);
cudaMemcpy(&time, dev_time, sizeof(long), cudaMemcpyDeviceToHost);
cudaMemcpy(&uni, unique, sizeof(int), cudaMemcpyDeviceToHost);
cudaFree(&dev_a);
cudaFree(&dev_b);
cudaFree(&dev_time);
cudaFree(&unique);
printf("%d\n", time);
printf("unique: %d\n", uni);
cudaDeviceReset();
}
return 0;
}
【问题讨论】:
-
为什么要在 CUDA 代码中获取该信息?为什么不能从 CPU 调用并传入 GPU?
-
我知道我可以从 CPU 传递它,但对于我的项目,出于安全原因,有必要在设备本身中收集信息。