【发布时间】:2021-06-28 03:04:52
【问题描述】:
#include <vector_functions.h>
#include <vector_types.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <string>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
__device__ int foo[16];
__device__ int bar[16];
__global__ void go(const int* ptr) {
printf("device: tid = %d, foo = %p\n", blockIdx.x, foo);
printf("device: tid = %d, ptr = %p\n", blockIdx.x, ptr);
int val = threadIdx.x;
for (int i = 0; i < (1 << 20); i++) {
bar[blockIdx.x] = val;
val = (val * 19 + ptr[threadIdx.x]) % (int)(1e9 + 7); // change ptr to foo for experiment
}
}
int main() {
int* ptr = nullptr;
cudaGetSymbolAddress((void**)&ptr, foo);
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start);
go<<<16, 16>>>(ptr);
cudaEventRecord(stop);
cudaEventSynchronize(stop);
cudaDeviceSynchronize();
float ms;
cudaEventElapsedTime(&ms, start, stop);
printf("%.6fms\n", ms);
return 0;
}
在我的 GeForce GTX 1080 上:
使用ptr 需要180 毫秒,但使用foo 只需要36 毫秒,尽管ptr 和foo 指向完全相同的地址。我认为它们应该以相同的速度执行,因为它们都是 L2 缓存的全局内存。
我使用的是Linux,我的编译命令是:
nvcc -gencode=arch=compute_61,code=compute_61 -Xptxas -O3 test.cu -o test
谁能解释一下原因?
【问题讨论】:
标签: c++ pointers caching cuda restrict-qualifier