【发布时间】:2021-05-13 14:03:47
【问题描述】:
我按照this page 上的教程进行操作,但结果很糟糕。所用时间如下:
CPU: 569
GPU: 11160
这是我的代码。出了什么问题?我不明白为什么这段代码这么慢?
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <chrono>
#include <iostream>
#include <math.h>
#include <stdio.h>
__global__ void addCUDA(int n, float* x, float* y)
{
int index = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
for (int i = index; i < n; i += stride)
y[i] = x[i] + y[i];
}
void add(int n, float* x, float* y)
{
for (int i = 0; i < n; i++)
y[i] = x[i] + y[i];
}
int main()
{
int N = 1 << 20;
float* x = new float[N];
float* y = new float[N];
for (int i = 0; i < N; i++) {
x[i] = 1.0f;
y[i] = 2.0f;
}
auto t1 = std::chrono::high_resolution_clock::now();
add(N, x, y);
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
float maxError = 0.0f;
for (int i = 0; i < N; i++)
maxError = fmax(maxError, fabs(y[i] - 3.0f));
std::cout << "Max error: " << maxError << std::endl;
std::cout << duration << std::endl;
delete[] x;
delete[] y;
float* u,
float* v;
cudaMallocManaged(&u, N * sizeof(float));
cudaMallocManaged(&v, N * sizeof(float));
for (int i = 0; i < N; i++) {
u[i] = 1.0f;
v[i] = 2.0f;
}
int blockSize = 256;
int numBlocks = (N + blockSize - 1) / blockSize;
int device = -1;
cudaGetDevice(&device);
cudaMemPrefetchAsync(u, N * sizeof(float), device, NULL);
cudaMemPrefetchAsync(v, N * sizeof(float), device, NULL);
auto t3 = std::chrono::high_resolution_clock::now();
addCUDA<<<numBlocks, blockSize>>> (N, u, v);
cudaDeviceSynchronize();
auto t4 = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(t4 - t3).count();
maxError = 0.0f;
for (int i = 0; i < N; i++)
maxError = fmax(maxError, fabs(v[i] - 3.0f));
std::cout << "Max error: " << maxError << std::endl;
std::cout << duration << std::endl;
cudaFree(u);
cudaFree(v);
return 0;
}
【问题讨论】:
-
您的代码似乎有错字:
float* u,,应该是分号。解决这个问题,当我在 linux V100 GPU 上按原样运行您的代码时,我得到 CPU:972,GPU:1085。当我在预取调用之后添加cudaDeviceSynchronize()时,如答案中所建议的,我得到 CPU:966 ,GPU:193。此外,您似乎在 Windows 上。我希望在 Windows 上有不同的行为。 GPU 类型很重要,编译类型/项目配置很重要,平台很重要。