【问题标题】:Comparsion in cuda [closed]cuda中的比较[关闭]
【发布时间】:2013-03-15 04:14:55
【问题描述】:

我必须在 CUDA 中比较两个浮点数组 (a,b),这样
if a > b then a = a/a ; else a = 0

请说出正确的调用方式和语法。

【问题讨论】:

  • a = a/a 是什么意思?不就是说 a = 1 吗?
  • 是 a=a/a 表示 1,基本上如果 a[i]>b[i],我想返回值 1,否则返回 0,我想对所有索引重复值(比如 20)
  • 先生,基本上我使用的是 CUFFT 库。因为我有两个输出,我必须比较 4096 个索引值。所以请指导我。

标签: cuda compare


【解决方案1】:

这样的事情应该可以工作。为了简洁起见,我正在简化我通常的 cuda 错误检查。

#include <stdio.h>
#define DSIZE 10000
#define nTPB 512

__global__ void cmp(float *a, float *b, int size){
  int idx = threadIdx.x + blockDim.x*blockIdx.x;
  if (idx < size)
    a[idx]=(a[idx] > b[idx])?1.0f:0.0f;  // could also be: ?(a[idx]/a[idx]):0;
}

int main() {
  cudaError_t err;
  float *h_a, *h_b, *d_a, *d_b;
  h_a = (float *)malloc(DSIZE*sizeof(float));
  if (h_a == 0) {printf("malloc fail\n"); return 1;}
  h_b = (float *)malloc(DSIZE*sizeof(float));
  if (h_b == 0) {printf("malloc fail\n"); return 1;}
  for (int i=0; i< DSIZE; i++){
    h_a[i] = 10.0f;
    h_b[i] = (float)i;}
  err = cudaMalloc((void **)&d_a, DSIZE*sizeof(float));
  if (err != cudaSuccess) {printf("cuda fail\n"); return 1;}
  err = cudaMalloc((void **)&d_b, DSIZE*sizeof(float));
  if (err != cudaSuccess) {printf("cuda fail\n"); return 1;}
  err = cudaMemcpy(d_a, h_a, DSIZE*sizeof(float), cudaMemcpyHostToDevice);
  if (err != cudaSuccess) {printf("cuda fail\n"); return 1;}
  err = cudaMemcpy(d_b, h_b, DSIZE*sizeof(float), cudaMemcpyHostToDevice);
  if (err != cudaSuccess) {printf("cuda fail\n"); return 1;}

  cmp<<<(DSIZE+nTPB-1)/nTPB, nTPB>>>(d_a, d_b, DSIZE);
  err=cudaMemcpy(h_a, d_a, DSIZE*sizeof(float), cudaMemcpyDeviceToHost);
  if (err != cudaSuccess) {printf("cuda fail\n"); return 1;}
  for (int i=0; i< 20; i++)
    printf("h_a[%d] = %f\n", i, h_a[i]);
  return 0;
}

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 2011-10-21
    • 2010-09-07
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多