-
Notifications
You must be signed in to change notification settings - Fork 41
Example C code
Nico edited this page Jun 29, 2020
·
2 revisions
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <math.h>
#include <hipsparse.h>
using namespace std;
int main()
{
int N = 10240;
int nnz = 256;
float alpha = 10.0f;
float tolerance = 1e-8f;
vector<int> hx_ind(nnz);
vector<float> hx_val(nnz);
vector<float> hy(N);
// Allocate memory on the device
int* dx_ind;
float* dx_val;
float* dy;
hipMalloc(&dx_ind, nnz * sizeof(int));
hipMalloc(&dx_val, nnz * sizeof(float));
hipMalloc(&dy, N * sizeof(float));
// Initial Data on CPU,
srand(1);
for(int i = 0; i < nnz; ++i)
{
hx_ind[i] = i * 40;
hx_val[i] = rand() % 10 + 1; // Generate an integer number between [1, 10]
}
for(int i = 0; i < N; ++i)
{
hy[i] = rand() % 10 + 1; // Generate an integer number between [1, 10]
}
// Copy data to device
hipMemcpy(dx_ind, hx_ind.data(), sizeof(int) * nnz, hipMemcpyHostToDevice);
hipMemcpy(dx_val, hx_val.data(), sizeof(float) * nnz, hipMemcpyHostToDevice);
hipMemcpy(dy, hy.data(), sizeof(float) * N, hipMemcpyHostToDevice);
// Initialize rocSPARSE
hipsparseHandle_t handle;
hipsparseCreate(&handle);
// Run saxpyi on device
hipsparseSaxpyi(handle, nnz, &alpha, dx_val, dx_ind, dy, HIPSPARSE_INDEX_BASE_ZERO);
// Copy output from device memory to host memory
vector<float> result(N);
hipMemcpy(result.data(), dy, sizeof(float) * N, hipMemcpyDeviceToHost);
// Verify hipsparseSaxpyi result
for(int i = 0; i < nnz; ++i)
{
hy[hx_ind[i]] += alpha * hx_val[i];
}
float error;
for(int i = 0; i < N; ++i)
{
error = fabs(hy[i] - result[i]);
if(error > tolerance)
{
fprintf(stderr, "Error in element %d: CPU=%f, GPU=%f\n", i, hy[i], result[i]);
break;
}
}
if(error > tolerance)
{
printf("axpyi test failed!\n");
}
else
{
printf("axpyi test passed!\n");
}
hipFree(dx_ind);
hipFree(dx_val);
hipFree(dy);
hipsparseDestroy(handle);
return 0;
}
First, paste above code into a file hipsparseSaxpyi_example.cpp
.
To compile hipsparseSaxpyi_example.cpp
, a standard C++ compiler can be used (e.g. g++):
g++ -O3 -o hipsparseSaxpyi_example hipsparseSaxpyi_example.cpp -D__HIP_PLATFORM_HCC__ -I/opt/rocm/include -L/opt/rocm/lib -lhipsparse -lamdhip64