4

以下是一个 CUDA 编程示例,它基本上是 C 语言,但其中包含 NVidia CUDA 函数。我一直在尝试解释这个代码示例并弄清楚它想要做什么。我的问题是这个程序编译得很好,但它需要什么参数?例如,这个 CUDA 程序正在 Linux 模拟器中运行,但是在运行 ./program 时它会返回:

用法:./program number 分段错误

程序输入参数是什么。谢谢你。

#include <assert.h>
#include <stdio.h>

//#define N 100000

__host__ void saxpy_host(int length, float alpha, float * x, float * y)
{
    for (int i = 0; i < length; ++i)
    y[i] = alpha*x[i] + y[i];
}

__global__ void saxpy (int length, float alpha, float * x, float * y)
{
   int i;
   i = blockIdx.x*blockDim.x + threadIdx.x;
   if (i < length) y[i] = alpha*x[i]+y[i];
   __syncthreads();
}

int main(int argc, char* argv[]) {

if (argc != 2) { 
  printf("Usage: %s number\n", argv[0]);
  return -1;
}

int N = atoi(argv[1]);

// host data
float alpha = 0.5;
float x[N], xback[N];
float y[N], yback[N];

int size;
int i;
int blocks;

// determining size 
size = sizeof(float)*N;


// device data
float * dxp, * dyp;


// fill host data
for (i = 0; i < N; i++) {
   x[i] = (float) (rand () % 128);
   y[i] = (float) (rand () % 256);
}


// Allocating and Moving data to device
cudaMalloc((void**) &dxp, size);
cudaMalloc((void**) &dyp, size);
cudaMemcpy (dxp, x, size, cudaMemcpyHostToDevice);
cudaMemcpy (dyp, y, size, cudaMemcpyHostToDevice);

// size of thread blocks
blocks = (N + 31)/32;
saxpy <<< blocks, 32 >>> (N, alpha, dxp, dyp);

// bring back data
cudaMemcpy (xback, dxp, size, cudaMemcpyDeviceToHost); 
cudaMemcpy (yback, dyp, size, cudaMemcpyDeviceToHost);

// Calculating host SAXPY
saxpy_host (N, alpha, (float *) &x, (float *) &y);

// checking computation on host matches computation on GPU
for (i = 0; i < N; i++) {
  assert (yback[i] == y[i]) ;
  //printf ("%i %f %f \n", i, yback[i], y[i]);
}


// free device data
cudaFree(dxp); cudaFree(dyp);

return 0;
}
4

1 回答 1

3
int N = atoi(argv[1]);

该程序将单个整数作为命令行参数。(例如,尝试将其称为./program 5。)

然后它计算一个 SAXPY(一个源自早期 BLAS 实现的旧术语,但它卡住了。它的意思是“单个(精度,又名浮点)实数 alpha x 加 y”。)带有维度向量N

于 2013-03-15T20:07:14.253 回答