-
Notifications
You must be signed in to change notification settings - Fork 39
Example code
Nico edited this page Jul 23, 2018
·
2 revisions
#include <iostream>
#include <cstdlib>
#include <rocalution.hpp>
using namespace rocalution;
int main(int argc, char* argv[])
{
if(argc == 1)
{
std::cerr << argv[0] << " <matrix> [Num threads]" << std::endl;
exit(1);
}
// Initialize rocALUTION
init_rocalution();
if(argc > 2)
{
set_omp_threads_rocalution(atoi(argv[2]));
}
// Print rocALUTION backend info
info_rocalution();
// rocALUTION objects
LocalMatrix<double> mat;
LocalVector<double> rhs;
LocalVector<double> x;
LocalVector<double> e;
// Read mtx matrix from file
mat.ReadFileMTX(std::string(argv[1]));
// Move rocALUTION objects to accelerator device (if available)
mat.MoveToAccelerator();
x.MoveToAccelerator();
rhs.MoveToAccelerator();
e.MoveToAccelerator();
// Allocate vectors
x.Allocate("x", mat.GetN());
rhs.Allocate("rhs", mat.GetM());
e.Allocate("e", mat.GetN());
// Linear Solver
CG<LocalMatrix<double>, LocalVector<double>, double> ls;
// Preconditioner
Jacobi<LocalMatrix<double>, LocalVector<double>, double> p;
// Generate rhs vector such that x = 1
e.Ones();
mat.Apply(e, &rhs);
x.Zeros();
// Set solver operator
ls.SetOperator(mat);
// Set solver preconditioner
ls.SetPreconditioner(p);
// Build solver and preconditioner
ls.Build();
// Verbose output
ls.Verbose(2);
// Print matrix info
mat.Info();
// Start time measurement
double tick, tack;
tick = rocalution_time();
// Solve linear system Ax = rhs
ls.Solve(rhs, &x);
// End time measurement
tack = rocalution_time();
std::cout << "Solver execution:" << (tack - tick) / 1000000 << " sec" << std::endl;
// Clear solver
ls.Clear();
// Compute L2 norm of then error
e.ScaleAdd(-1.0, x);
double error = e.Norm();
std::cout << "||e - x||_2 = " << error << "\n";
// Stop rocALUTION
stop_rocalution();
return 0;
}
To compile and run the example, past above code into a file rocalution_cg_example.cpp
.
To compile rocalution_cg_example.cpp
, a standard C++ compiler can be used (e.g. g++):
g++ -O3 -o rocalution_cg_example rocalution_cg_example.cpp -I/opt/rocm/include -L/opt/rocm/lib -lrocalution
The compiled rocalution_cg_example
can be executed by
./rocalution_cg_example <matrix.mtx>
where matrix.mtx is a matrix in Matrix-Market format. Different matrices can be obtained from e.g. SuiteSparse Matrix Collection.