archrelease: copy trunk to community-any
[ArchLinux/community.git] / hipsparse / repos / community-x86_64 / test.cpp
blobcd14f2ee6ea50daada890a12ea536d2b96e1bfe6
1 #include <hipsparse/hipsparse.h>
2 #include <hip/hip_runtime.h>
3 #include <iostream>
4 #include <vector>
5 #include <random>
6 #include <algorithm>
8 int main()
10 int n = 1024;
12 std::random_device rd;
13 std::mt19937 gen(rd());
14 std::uniform_real_distribution<float> dist(-1.0, 1.0);
16 auto myrand = [&]() -> float {return dist(gen);};
18 std::vector<float> xin(n);
19 std::generate(xin.begin(), xin.end(), myrand);
21 hipsparseHandle_t handle;
22 hipsparseCreate(&handle);
24 std::vector<int> row_ptr(n + 1);
25 std::vector<int> col(3 * n);
26 std::vector<float> data(3 * n);
28 //Second order finite differences matrix in 1D
29 row_ptr[0] = 0;
30 for(size_t i = 0; i < n; i++){
31 int off = row_ptr[i];
32 if(i > 0){
33 col[off] = i - 1;
34 data[off++] = -1.0f;
36 col[off] = i;
37 data[off++] = 2.0f;
38 if(i < n - 1){
39 col[off] = i + 1;
40 data[off++] = -1.0f;
42 row_ptr[i + 1] = off;
45 int *rp;
46 int *c;
47 float *d;
49 float *x;
50 float *y;
51 hipMalloc((void **)&rp, sizeof *rp * (n + 1));
52 hipMalloc((void **)&c, sizeof *c * 3 * n);
53 hipMalloc((void **)&d, sizeof *d * 3 * n);
55 hipMalloc((void **)&x, sizeof *x * n);
56 hipMalloc((void **)&y, sizeof *y * n);
58 hipMemcpy(rp, row_ptr.data(), sizeof *rp * (n + 1), hipMemcpyHostToDevice);
59 hipMemcpy(c, col.data(), sizeof *c * 3 * n, hipMemcpyHostToDevice);
60 hipMemcpy(d, data.data(), sizeof *d * 3 * n, hipMemcpyHostToDevice);
62 hipMemcpy(x, xin.data(), sizeof *x * n, hipMemcpyHostToDevice);
64 float alpha = 14.124f;
65 float beta = 0.0f;
67 hipsparseMatDescr_t descr;
68 hipsparseCreateMatDescr(&descr);
70 hipsparseScsrmv(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE,
71 n, n, 3 * n - 2, &alpha, descr, d, rp, c,
72 x, &beta, y);
74 std::vector<float> yout(n);
75 hipMemcpy(yout.data(), y, sizeof *y * n, hipMemcpyDeviceToHost);
77 float tol = 0.0001f;
78 for(int i = 0; i < n; i++){
79 for(int jj = row_ptr[i]; jj < row_ptr[i + 1]; jj++){
80 int j = col[jj];
81 yout[i] -= alpha * data[jj] * xin[j];
83 if(std::abs(yout[i]) > tol){
84 std::cout << "Entry " << i << " is not computed correctly.\n";
85 std::cout << "Expected 0 but got " << yout[i] << std::endl;
86 return 1;
90 std::cout << "TESTS PASSED!" << std::endl;
92 hipsparseDestroy(handle);
93 hipsparseDestroyMatDescr(descr);
94 hipFree(rp);
95 hipFree(c);
96 hipFree(d);
97 hipFree(x);
98 hipFree(y);