cublasIsamax()程序运行结果不对

现在正在看CUBLAS_Library这个手册,看到cublasIsamax()的时候,自己写了一段小程序,为什么结果不稳定,一次运行一个结果,是不是我理解错了cublasStatus_t cublasIsamax(cublasHandle_t handle,int n,const floatx,int incx,intresult)
中的result这个变量?下面这个例子我将result定义为int result=(int)malloc(sizeof(int));我不知道该将result定义多大才好,我第一次是这样定义result的:int result=(int)malloc(length*sizeof(int));.

我的问题是result输出的到底是什么值?它该定义为多大?我自己的理解是result输出一个向量中最大元素那个值的下标,如果两个值一样大,就输出那个最小的下标。

#include “cuda_runtime.h”
#include “device_launch_parameters.h”
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cublas_v2.h>
const int length=10;

int main(void)
{
cudaError_t cudaStat;
cublasStatus_t stat;
cublasHandle_t handle;
int i,j;
int result=(int)malloc(sizeof(int));
float* devPtrA;
float* a=0;
a=(float*)malloc(length*sizeof(*a));
if(!a)
{
printf(“host memory allocation failed”);
return EXIT_FAILURE;
}

for(i=0;i<length;i++)
{
a[i]=(float)(i5+2);
}
cudaStat=cudaMalloc((void**)&devPtrA,length
sizeof(*a));
if(cudaStat!=cudaSuccess)
{
printf(“device memory allocation failed”);
return EXIT_FAILURE;
}
stat=cublasCreate(&handle);
if(stat!=CUBLAS_STATUS_SUCCESS)
{
printf(“CUBLAS initialization failed\n”);
return EXIT_FAILURE;
}
stat=cublasIsamax(handle,length,devPtrA,1,result);
if(stat!=CUBLAS_STATUS_SUCCESS)
{
printf(“data download failed”);
cudaFree(devPtrA);
cublasDestroy(handle);
return EXIT_FAILURE;
}
cudaFree(devPtrA);
cublasDestroy(handle);

printf("%d ",result[0]);

printf(“\n”);

free(a);
free(result);

return EXIT_SUCCESS;
}

欢迎楼主莅临!

您的代码和理解有问题存在:
(1)您的在host memory上构造好的a和您的device memory上的devPtrA指向的内存毫无关系。后者在您的代码中,指向的内容必然是随机值,导致你的result也是随机值。所以导致了您的“为何结果不稳定”的结论。
(2)元素不是最大值,而是其绝对值最大。

如下2建议可能对您适用:
(1)使用cudaMemcpy, 以使得您的devPtrA指向的内容和您构造的值一样。
(2)在脑海中修正理解为绝对值。

其他的1可选建议:
一般的,sizeof常用的是sizeof(type)。这是较为常见的用法,建议您修正为此。

祝您编写愉快!

少回复了一个问题(不好意思看漏了):
您的result用的没错。
除了您的int * result = (int *)malloc(sizeof(int))外,
您还可以简单的:int result; 然后用&result即可。

太好了,能够正确运行了!非常感谢!类似的amin(),asum()都能得到正确结果了,太兴奋了~

恭喜楼主修得“BUG退散,风轻云淡”成就!
欢迎常来论坛!
祝您编码愉快~

(前面点击“回复”的时候误点为“编辑”,所以4#显示为被我编辑过,实际内容无更改。抱歉!)

恭喜楼主,贺喜楼主!

能不能不运行正确的源码发过来,让我运行以下??谢谢

您好:

此帖已经过去半年多了,请勿挖坟,您可以论坛私信联系LZ索要代码。

此帖将做下沉处理。