Most matrices in actual packages are principally zeros, and a sparse matrix format shops solely the values that aren’t zero. The work is in recording the place these values sit. This text builds the three customary codecs in C and measures them in opposition to a plain dense array. On a 1024 by 1024 matrix with 1 p.c of its cells crammed, the compressed sparse row format (CSR) used 129,932 bytes the place the dense array used 8,388,608, and it multiplied the matrix by a vector 105.79 occasions sooner than the dense loop. At 50 p.c crammed, CSR nonetheless used three quarters of the dense reminiscence and was solely twice as quick.
The article covers the coordinate format (COO), CSR and the compressed sparse column format (CSC). For each it reveals how the format is constructed from an inventory of entries, the way it multiplies a vector, and the way a lot reminiscence it wants. It then measures reminiscence and multiply time at 1, 10 and 50 p.c density, and ends with 5 bugs that compile cleanly and provides mistaken solutions. The Arrays article covers the dense array used because the baseline. The code was constructed and examined with GCC 13.3, Clang 18.1.3 and MSVC 19.44.
What Is a Sparse Matrix?
A sparse matrix is a matrix with so few nonzero values that it’s cheaper to retailer every worth with its place than to retailer each cell. The three customary codecs are COO, which retains a row, a column and a worth for every nonzero, CSR, which teams the values by row and replaces the row numbers with one pointer per row, and CSC, which does the identical by column.
Whether or not a matrix is sparse sufficient is a matter of arithmetic. A dense n by n matrix of double values takes 8n² bytes. COO takes 16 bytes per nonzero: two 4-byte indexes and an 8-byte worth. CSR and CSC take 12 bytes per nonzero, one index and one worth, plus 4 bytes for every of the n + 1 pointers. For n = 1024, CSR is smaller than the dense array till about two thirds of the cells, 66.6 p.c, are nonzero. Actual sparse matrices are often far beneath that line.
The three codecs maintain the identical information and differ in what they make quick. CSR retains every row’s values collectively, so a matrix-vector product y = A x reads them so as and writes every y[row] as soon as. CSC retains every column’s values collectively, which fits algorithms that work column by column. COO is the best to construct, as a result of new entries are merely appended, however its product has to learn a row index for each worth.
Sparse matrices are all over the place in apply. The adjacency matrix of a giant graph is sort of all zeros, and CSR is similar thought as an adjacency checklist packed into two arrays. Finite component fashions, suggestion information and phrase counts per doc are sparse in the identical approach. The Wikipedia article covers the broader household of codecs.
How This Was Measured
| Setting | Worth |
|---|---|
| Date examined | December 5, 2026 |
| {Hardware} | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Home windows 11 Schooling construct 26300 |
| Working system | Ubuntu 24.04.5 underneath WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39, and Home windows 11 for the MSVC construct |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 by means of CMake Launch, MSVC 19.44 at /W4 /WX |
| Matrix | 1024 by 1024, so 1,048,576 cells, one fastened matrix per density |
| Densities | 1, 10 and 50 p.c of the cells crammed, at distinct positions |
| Generator | xorshift64 with seed 88172645463325252, values from -10.00 to 10.00 in steps of 0.01 |
| Merchandise | y = A x with x[i] = (i % 7 – 3) × 0.5, timed over 100 merchandise per format and density |
| Outcomes | Allotted bytes per format, complete milliseconds for 100 merchandise, and CSR’s speedup over dense |
| Examine | Each sparse product is in contrast with the dense product earlier than timing, and the biggest distinction is printed |
The matrices are generated from a hard and fast seed, so the nonzero counts and the byte counts are the identical on each run. The occasions are usually not. They depend upon the machine and differ from run to run, so the exams examine the desk’s structure and its fastened columns however by no means a time. The occasions beneath come from one run.
COO: Coordinate Triplets
COO shops three arrays of equal size: the row of every nonzero, its column and its worth. Constructing one means appending entries, very similar to a dynamic array. Matrix recordsdata often arrive on this kind, and two COO matrices might be added by becoming a member of their arrays.
Earlier than COO is used for the rest, the builder kinds the entries by row after which by column and merges repeated positions by including their values. Enter typically comprises the identical cell twice, for instance when a finite component program provides the contributions of neighboring components to 1 cell. The conference is that repeated entries are summed.
A COO product that merely provides each entry follows that conference and will get the suitable reply even with duplicates left in. The difficulty begins in code that assumes every cell seems as soon as. A conversion to a dense array that assigns values as a substitute of including them retains solely one of many duplicates, and the nonzero depend is just too excessive. The third pitfall reveals that failure.
CSR: Compressed Sparse Row
CSR retains the values sorted by row and shops no row numbers in any respect. As a substitute, an array of n + 1 row pointers marks the place every row begins: row r occupies positions row_ptr[r] as much as, however not together with, row_ptr[r + 1]. The additional ultimate pointer equals the variety of nonzeros, so the final row has an finish. Every nonzero prices one column index and one worth.
The product follows the structure. For every row, the loop walks that row’s values and column indexes in reminiscence order, multiplies every worth by x[col], provides it to a operating sum, and shops the sum in y[row]. The reads of the values and indexes are sequential, and y is written as soon as per row. Solely the reads of x bounce round, following the column indexes.
CSR is probably the most extensively used general-purpose sparse format, though some libraries, similar to SuiteSparse and Eigen, default to CSC. CSR’s weak point is change: inserting one nonzero means shifting each later worth and including 1 to each later row pointer. CSR fits a matrix that’s constructed as soon as after which multiplied many occasions.
CSC: Compressed Sparse Column
CSC is CSR utilized to columns. The values are sorted by column, an array of n + 1 column pointers marks the place every column begins, and every nonzero shops its row index. The reminiscence is an identical to CSR. Actually, the CSC arrays of a matrix A are precisely the CSR arrays of its transpose.
For y = A x, the CSC loop walks one column at a time. Every worth in column c is multiplied by x[c], which stays fastened for the entire column, and added into y on the worth’s row. The reads are sequential, however the writes to y bounce from row to row. CSC is the pure format when an algorithm wants entire columns, as many sparse factorization strategies do.
The selection between CSR and CSC is about which loop comes first, rows or columns. Each retailer the identical numbers in the identical quantity of reminiscence.
Selecting a Format
Begin with the density. If CSR is smaller than the dense array, which for this matrix measurement means beneath about two thirds full, a sparse format saves reminiscence. Then have a look at velocity individually. At 50 p.c density CSR used 75 p.c of the dense reminiscence and was solely twice as quick, so a easy dense array is an inexpensive alternative for a matrix that full.
Subsequent, match the format to the work. Row-by-row algorithms and the bizarre y = A x product go well with CSR, and column-by-column algorithms go well with CSC. Whereas a matrix continues to be being assembled, merged or learn from a file, maintain it in COO and convert it to CSR or CSC as soon as it’s full. If the construction retains altering, a hash desk keyed by row and column is a versatile strategy to acquire entries earlier than the conversion.
For actual take a look at information, the SuiteSparse Matrix Assortment gives hundreds of matrices from actual functions. This text makes use of generated matrices so the density might be set precisely. In Python, SciPy’s sparse module supplies the identical three codecs.
Implementation in C
The C code retains one struct per format: COO with row, column and worth arrays, CSR with values, column indexes and row pointers, and CSC with values, row indexes and column pointers. A plain dense array serves because the reference for checking each product. The builder beneath copies the enter entries, rejects positions exterior the matrix, kinds the entries, and merges repeated positions by including their values.
bool coo_build(Coo *coo, int n, const Triple *triplets, int depend)
{
Triple *sorted = NULL;
int index;
int nnz;
if (coo == NULL)
return false;
coo_clear(coo);
if (n <= 0 || depend < 0 || (depend > 0 && triplets == NULL))
return false;
if (depend == 0) {
coo->n = n;
return true;
}
sorted = malloc((size_t)depend * sizeof *sorted);
coo->row = malloc((size_t)depend * sizeof *coo->row);
coo->col = malloc((size_t)depend * sizeof *coo->col);
coo->val = malloc((size_t)depend * sizeof *coo->val);
if (sorted == NULL || coo->row == NULL || coo->col == NULL ||
coo->val == NULL) {
free(sorted);
coo_free(coo);
return false;
}
memcpy(sorted, triplets, (size_t)depend * sizeof *sorted);
for (index = 0; index < depend; ++index) {
if (sorted[index].row < 0 || sorted[index].row >= n ||
sorted[index].col < 0 || sorted[index].col >= n) {
free(sorted);
coo_free(coo);
return false;
}
}
qsort(sorted, (size_t)depend, sizeof *sorted, compare_triples);
nnz = 0;
for (index = 0; index < depend; ++index) {
if (nnz > 0 && coo->row[nnz - 1] == sorted[index].row &&
coo->col[nnz - 1] == sorted[index].col) {
coo->val[nnz - 1] += sorted[index].worth;
} else {
coo->row[nnz] = sorted[index].row;
coo->col[nnz] = sorted[index].col;
coo->val[nnz] = sorted[index].worth;
nnz++;
}
}
free(sorted);
coo->n = n;
coo->nnz = nnz;
coo->row = shrink_block(coo->row, (size_t)nnz * sizeof *coo->row);
coo->col = shrink_block(coo->col, (size_t)nnz * sizeof *coo->col);
coo->val = shrink_block(coo->val, (size_t)nnz * sizeof *coo->val);
return true;
}
The conversion to CSR follows the three steps within the apart above: depend the entries per row, flip the counts into operating totals, and place every entry.
bool coo_to_csr(const Coo *coo, Csr *csr)
{
int *subsequent = NULL;
int row;
int index;
int nnz;
if (coo == NULL || csr == NULL || coo->n <= 0 || coo->nnz < 0)
return false;
csr_clear(csr);
nnz = coo->nnz;
csr->row_ptr = calloc((size_t)coo->n + 1, sizeof *csr->row_ptr);
if (nnz > 0) {
csr->val = malloc((size_t)nnz * sizeof *csr->val);
csr->col_idx = malloc((size_t)nnz * sizeof *csr->col_idx);
subsequent = malloc((size_t)coo->n * sizeof *subsequent);
}
if (csr->row_ptr == NULL || (nnz > 0 && (csr->val == NULL ||
csr->col_idx == NULL ||
subsequent == NULL))) {
free(subsequent);
csr_free(csr);
return false;
}
for (index = 0; index < nnz; ++index)
csr->row_ptr[coo->row[index] + 1]++;
for (row = 0; row < coo->n; ++row)
csr->row_ptr[row + 1] += csr->row_ptr[row];
if (nnz > 0) {
memcpy(subsequent, csr->row_ptr, (size_t)coo->n * sizeof *subsequent);
for (index = 0; index < nnz; ++index) {
int at = subsequent[coo->row[index]]++;
csr->val[at] = coo->val[index];
csr->col_idx[at] = coo->col[index];
}
free(subsequent);
}
csr->n = coo->n;
csr->nnz = nnz;
return true;
}
The CSR product computes one row sum at a time.
void spmv_csr(const Csr *csr, const double *x, double *y)
{
int row;
for (row = 0; row < csr->n; ++row) {
double sum = 0.0;
int at;
for (at = csr->row_ptr[row]; at < csr->row_ptr[row + 1]; ++at)
sum += csr->val[at] * x[csr->col_idx[at]];
y[row] = sum;
}
}
The demo builds the 4 by 4 matrix from Determine 1, prints all three codecs, and multiplies by a vector of ones. Every worth of y is the sum of 1 row.
sparse matrix: COO, CSR and CSC
matrix 4x4, nnz 5
COO rows: 0 0 1 2 3
COO cols: 0 3 1 2 3
COO vals: 1.50 5.50 2.50 3.50 4.50
CSR row_ptr: 0 2 3 4 5
CSR col_idx: 0 3 1 2 3
CSR values: 1.50 5.50 2.50 3.50 4.50
CSC col_ptr: 0 1 2 3 5
CSC row_idx: 0 1 2 0 3
CSC values: 1.50 2.50 3.50 5.50 4.50
y = A*x, x all ones: 7.00 2.50 3.50 4.50
max diff dense vs COO/CSR/CSC: 0.000000
Measured: Reminiscence Towards Dense
The reminiscence experiment builds each format from the identical generated matrix at every density and experiences the bytes each allocates. It additionally checks the byte counts in opposition to the formulation from the definition part, so a measurement that disagrees with the arithmetic stops this system.
static void run_row(const Density *density)
int predominant(void)
{
int row;
printf("matrix %dxpercentd, entries %d, dense bytes %zun", N, N, CELLS,
dense_bytes(N));
printf("%-9s%-9s%-13s%-11s%-11s%-11spercentsn", "density", "nnz", "dense_bytes",
"coo_bytes", "csr_bytes", "csc_bytes", "csr_vs_dense");
for (row = 0; row < DENSITY_ROWS; ++row)
run_row(&DENSITIES[row]);
return EXIT_SUCCESS;
}
Output:
matrix 1024x1024, entries 1048576, dense bytes 8388608
density nnz dense_bytes coo_bytes csr_bytes csc_bytes csr_vs_dense
1% 10486 8388608 167776 129932 129932 0.015
10% 104858 8388608 1677728 1262396 1262396 0.150
50% 524288 8388608 8388608 6295556 6295556 0.750
The measured sizes match the formulation precisely. The dense array is 8,388,608 bytes at each density. CSR and CSC want 129,932 bytes at 1 p.c, 0.015 of the dense measurement, then 1,262,396 bytes at 10 p.c (0.150) and 6,295,556 bytes at 50 p.c (0.750).
COO wants 16 bytes per nonzero, so it takes 167,776 bytes at 1 p.c and 1,677,728 at 10 p.c. At 50 p.c it takes precisely 8,388,608 bytes, the identical because the dense array, as a result of 16 bytes occasions half the cells equals 8 bytes occasions all of them. CSR stays smaller than the dense array as much as 698,709 nonzeros, which is 66.6 p.c of the cells.
Measured: Matrix-Vector Multiply Time
The timing experiment first checks that each sparse product matches the dense product, after which occasions 100 merchandise in every format.
static double time_products(int format, const Coo *coo, const Csr *csr,
const Csc *csc, const double *dense,
const double *x, double *y)
{
double began;
double elapsed;
int run;
began = now_ms();
for (run = 0; run < RUNS; ++run) {
change (format) {
case 0:
spmv_dense(dense, N, x, y);
break;
case 1:
spmv_coo(coo, x, y);
break;
case 2:
spmv_csr(csr, x, y);
break;
default:
spmv_csc(csc, x, y);
break;
}
}
elapsed = now_ms() - began;
return elapsed;
}
static void run_row(const Density *density, double *differences_out)
Output:
matrix 1024x1024, 100 matrix-vector merchandise per format
density nnz dense_ms coo_ms csr_ms csc_ms csr_speedup
1% 10486 108.188 1.789 1.023 0.930 105.79
10% 104858 105.216 22.348 9.304 7.648 11.31
50% 524288 107.263 123.282 53.822 32.740 1.99
max diff vs dense, 1%: 0.000000
max diff vs dense, 10%: 0.000000
max diff vs dense, 50%: 0.000000
The dense product took between 105 and 108 milliseconds at each density, as a result of it at all times multiplies all 1,048,576 cells, zeros included. The sparse merchandise solely contact the nonzeros. At 1 p.c, CSR took 1.023 milliseconds, 105.79 occasions sooner than dense. At 10 p.c it took 9.304 milliseconds, 11.31 occasions sooner. At 50 p.c the hole almost closed: CSR took 53.822 milliseconds, just one.99 occasions sooner, and COO took 123.282 milliseconds, slower than the dense loop.
On this machine CSC was sooner than CSR in any respect three densities: 0.930, 7.648 and 32.740 milliseconds. That ordering didn’t maintain elsewhere. On a second Linux machine, a shared cloud server operating the GCC construct, CSR was sooner at 1 and 10 p.c and the 2 tied at 50 p.c.
A probable trigger is the processor’s skill to overlap work. CSR provides every row into one operating sum, so each addition waits for the earlier one, whereas CSC’s additions go to completely different rows and may overlap. How a lot that issues is determined by the processor. Deal with CSR and CSC as equally quick for this product, and select between them by entry sample.
5 Methods a Sparse Matrix Implementation Passes a Fast Check and Nonetheless Fails
Every program beneath compiles with out warnings and prints plausible output till a mistaken worth seems or the sanitizer stops it. The primary is caught by AddressSanitizer. The opposite 4 print a mistaken consequence subsequent to the right one.
1. A Row Pointer Array One Entry Too Brief
static void build_csr(int *col_idx, double *val)
{
int counts[N] = {0};
int subsequent[N];
risky int entries = ROW_PTR_ENTRIES;
int *row_ptr = malloc((size_t)entries * sizeof *row_ptr);
int index;
if (row_ptr == NULL)
fail("out of reminiscence for row_ptr");
for (index = 0; index < NNZ; ++index)
counts[COO_ROW[index]]++;
row_ptr[0] = 0;
for (index = 0; index < N; ++index)
row_ptr[index + 1] = row_ptr[index] + counts[index];
for (index = 0; index < N; ++index)
subsequent[index] = row_ptr[index];
for (index = 0; index < NNZ; ++index) {
int at = subsequent[COO_ROW[index]]++;
val[at] = COO_VAL[index];
col_idx[at] = COO_COL[index];
}
free(row_ptr);
}
int predominant(void)
{
int col_idx[NNZ];
double val[NNZ];
setvbuf(stdout, NULL, _IONBF, 0);
places("csr_row_ptr_short: a 4x4 matrix with 5 entries has row_ptr 0 2 3 4 5");
places("row_ptr wants n + 1 = 5 entries: one per row plus the row after the final");
places("the builder allocates row_ptr[4] and the prefix sum writes row_ptr[4], one previous the array");
places("constructing the CSR now");
build_csr(col_idx, val);
places("the write previous the array didn't fail loudly");
return EXIT_SUCCESS;
}
Output:
csr_row_ptr_short: a 4x4 matrix with 5 entries has row_ptr 0 2 3 4 5
row_ptr wants n + 1 = 5 entries: one per row plus the row after the final
the builder allocates row_ptr[4] and the prefix sum writes row_ptr[4], one previous the array
constructing the CSR now
AddressSanitizer then stops this system contained in the builder. Its report, summarized:
ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of measurement 4, 0 bytes after a 16-byte heap area
SUMMARY: AddressSanitizer: heap-buffer-overflow pitfalls/csr_row_ptr_short.c:59 in build_csr
The row pointer array wants n + 1 entries, as a result of every row’s finish is the subsequent row’s begin, and the final row wants an finish too. The damaged builder allocates solely n entries. The running-total loop then writes row_ptr[n], one component previous the tip of the array, and AddressSanitizer experiences a 4-byte heap-buffer-overflow write within the builder. With out the sanitizer, the write lands in no matter reminiscence follows the array and should go unnoticed. The repair is to allocate n + 1 entries.
2. A Row Loop That Skips Every Row’s First Entry
static void spmv_off_by_one(const double *val, const int *col_idx,
const int *row_ptr, const double *x, double *y)
{
int row;
for (row = 0; row < N; ++row) {
double sum = 0.0;
int at;
for (at = row_ptr[row] + 1; at < row_ptr[row + 1]; ++at)
sum += val[at] * x[col_idx[at]];
y[row] = sum;
}
}
/* The identical product with the row slice beginning at row_ptr[row]. */
static void spmv_correct(const double *val, const int *col_idx,
const int *row_ptr, const double *x, double *y)
{
int row;
for (row = 0; row < N; ++row) {
double sum = 0.0;
int at;
for (at = row_ptr[row]; at < row_ptr[row + 1]; ++at)
sum += val[at] * x[col_idx[at]];
y[row] = sum;
}
}
int predominant(void)
{
int row_ptr[N + 1];
int col_idx[NNZ];
double val[NNZ];
double x[N] = {1.0, 1.0, 1.0, 1.0};
double mistaken[N];
double appropriate[N];
build_csr(row_ptr, col_idx, val);
spmv_off_by_one(val, col_idx, row_ptr, x, mistaken);
spmv_correct(val, col_idx, row_ptr, x, appropriate);
places("csr_loop_off_by_one: the row loop begins at row_ptr[row] + 1");
print_y("mistaken y:", mistaken);
print_y("appropriate y:", appropriate);
return 0;
}
Output:
csr_loop_off_by_one: the row loop begins at row_ptr[row] + 1
mistaken y: 5.50 0.00 0.00 0.00
appropriate y: 7.00 2.50 3.50 4.50
The damaged loop begins every row at row_ptr[row] + 1 as a substitute of row_ptr[row], so it skips the primary entry of each row. Row 0 loses its 1.50 and retains solely 5.50. Rows 1 to three have one entry every, so that they lose every part and develop into 0.00. The right result’s 7.00, 2.50, 3.50 and 4.50. An off-by-one firstly of a row vary is simply as mistaken as one on the finish.
3. Duplicate Coordinates That Are Not Summed
static int build_coo_buggy(int *row, int *col, double *val)
{
int index;
for (index = 0; index < TRIPLET_COUNT; ++index) {
row[index] = TRIPLETS[index].row;
col[index] = TRIPLETS[index].col;
val[index] = TRIPLETS[index].worth;
}
return TRIPLET_COUNT;
}
static int build_coo_correct(int *row, int *col, double *val)
{
Triple sorted[TRIPLET_COUNT];
int nnz = 0;
int index;
int at;
for (index = 0; index < TRIPLET_COUNT; ++index) {
Triple key = TRIPLETS[index];
at = index;
whereas (at > 0 && (sorted[at - 1].row > key.row ||
(sorted[at - 1].row == key.row &&
sorted[at - 1].col > key.col))) {
sorted[at] = sorted[at - 1];
at--;
}
sorted[at] = key;
}
for (index = 0; index < TRIPLET_COUNT; ++index) {
if (nnz > 0 && row[nnz - 1] == sorted[index].row &&
col[nnz - 1] == sorted[index].col) {
val[nnz - 1] += sorted[index].worth;
} else {
row[nnz] = sorted[index].row;
col[nnz] = sorted[index].col;
val[nnz] = sorted[index].worth;
nnz++;
}
}
return nnz;
}
int predominant(void)
{
int row[TRIPLET_COUNT];
int col[TRIPLET_COUNT];
double val[TRIPLET_COUNT];
double dense[N * N];
double x[N] = {1.0, 1.0, 1.0, 1.0};
double mistaken[N];
double anticipated[N];
int buggy_nnz;
int correct_nnz;
buggy_nnz = build_coo_buggy(row, col, val);
coo_to_dense(row, col, val, buggy_nnz, dense);
spmv_dense(dense, x, mistaken);
correct_nnz = build_coo_correct(row, col, val);
coo_to_dense(row, col, val, correct_nnz, dense);
spmv_dense(dense, x, anticipated);
places("coo_duplicates_not_summed: the builder retains the repeated cell (0,0) "
"as two entries");
printf("buggy nnz %d, anticipated nnz %dn", buggy_nnz, correct_nnz);
print_y("mistaken y:", mistaken);
print_y("anticipated y:", anticipated);
return 0;
}
Output:
coo_duplicates_not_summed: the builder retains the repeated cell (0,0) as two entries
buggy nnz 6, anticipated nnz 5
mistaken y: 6.50 2.50 3.50 4.50
anticipated y: 7.00 2.50 3.50 4.50
The enter lists cell (0, 0) twice, first with 0.5 and later with 1.0, so the supposed worth is 1.5. The buggy builder retains each entries, which makes the nonzero depend 6 as a substitute of 5. The conversion to a dense array then assigns every entry to its cell, so the later 1.0 overwrites the 0.5. Row 0 sums to six.50 as a substitute of seven.00. A product that added each COO entry instantly would get 7.00, which is why this bug can disguise. It solely seems when later code assumes every cell happens as soon as.
4. A CSC Product That Writes to the Column As a substitute of the Row
static void spmv_column_as_row(const double *val, const int *row_idx,
const int *col_ptr, const double *x, double *y)
{
int col;
for (col = 0; col < N; ++col)
y[col] = 0.0;
for (col = 0; col < N; ++col) {
int at;
for (at = col_ptr[col]; at < col_ptr[col + 1]; ++at)
y[col] += val[at] * x[row_idx[at]];
}
}
/* The identical product writing every contribution to its saved row. */
static void spmv_correct(const double *val, const int *row_idx,
const int *col_ptr, const double *x, double *y)
{
int col;
for (col = 0; col < N; ++col)
y[col] = 0.0;
for (col = 0; col < N; ++col) {
int at;
for (at = col_ptr[col]; at < col_ptr[col + 1]; ++at)
y[row_idx[at]] += val[at] * x[col];
}
}
int predominant(void)
{
int col_ptr[N + 1];
int row_idx[NNZ];
double val[NNZ];
double x[N] = {1.0, 1.0, 1.0, 1.0};
double mistaken[N];
double appropriate[N];
build_csc(col_ptr, row_idx, val);
spmv_column_as_row(val, row_idx, col_ptr, x, mistaken);
spmv_correct(val, row_idx, col_ptr, x, appropriate);
places("csc_column_as_row: the CSC product writes y[col] as a substitute of "
"y[row_idx[at]]");
print_y("mistaken y:", mistaken);
print_y("appropriate y:", appropriate);
return 0;
}
Output:
csc_column_as_row: the CSC product writes y[col] as a substitute of y[row_idx[at]]
mistaken y: 1.50 2.50 3.50 10.00
appropriate y: 7.00 2.50 3.50 4.50
In CSC, every worth’s row index says which component of y it belongs to. The damaged loop provides the worth to y[col], the column being walked, as a substitute of y[row_idx[at]]. The result’s 1.50, 2.50, 3.50 and 10.00, as a result of column 3 holds 5.5 and 4.5. The right result’s 7.00, 2.50, 3.50 and 4.50. Each outcomes add as much as 17.50, so a take a look at that solely checks the full of y will cross. The damaged loop has the truth is computed the product with the transposed matrix.
5. A Dense Baseline Listed Column-Main
static void spmv_column_major(const double *dense, const double *x, double *y)
{
int row;
for (row = 0; row < N; ++row) {
double sum = 0.0;
int col;
for (col = 0; col < N; ++col)
sum += dense[col * N + row] * x[col];
y[row] = sum;
}
}
/* The identical product studying the cell at row * n + col. */
static void spmv_row_major(const double *dense, const double *x, double *y)
{
int row;
for (row = 0; row < N; ++row) {
double sum = 0.0;
int col;
for (col = 0; col < N; ++col)
sum += dense[row * N + col] * x[col];
y[row] = sum;
}
}
int predominant(void)
{
double dense[N * N];
double x[N] = {1.0, 1.0, 1.0, 1.0};
double mistaken[N];
double appropriate[N];
build_dense(dense);
spmv_column_major(dense, x, mistaken);
spmv_row_major(dense, x, appropriate);
places("dense_column_major_index: the dense baseline indexes a[col * n + row]");
print_y("mistaken y:", mistaken);
print_y("row-major y:", appropriate);
return 0;
}
Output:
dense_column_major_index: the dense baseline indexes a[col * n + row]
mistaken y: 1.50 2.50 3.50 10.00
row-major y: 7.00 2.50 3.50 4.50
A dense matrix saved row by row retains cell (row, col) at index row × n + col. The damaged baseline reads index col × n + row, which is the cell of the transposed matrix, so it additionally multiplies by the transpose and prints the identical mistaken consequence because the fourth pitfall. A bug within the reference is probably the most harmful sort. If each sparse product is checked in opposition to a transposed baseline, the right sparse code fails its exams, and a sparse product with the identical mistake passes.
Key Takeaways
- A sparse matrix shops solely its nonzero values and their positions. COO shops a row, column and worth for every, CSR teams them by row, and CSC teams them by column.
- In C, with 4-byte indexes and 8-byte values, COO prices 16 bytes per nonzero, CSR and CSC value 12 bytes per nonzero plus 4 bytes per row or column, and a dense matrix prices 8 bytes per cell.
- For a 1024 by 1024 matrix, CSR is smaller than the dense array as much as 66.6 p.c density. It was 0.015 of the dense measurement at 1 p.c and 0.750 at 50 p.c.
- CSR’s product was 105.79 occasions sooner than dense at 1 p.c, 11.31 occasions at 10 p.c and just one.99 occasions at 50 p.c, the place COO was slower than dense.
- CSR and CSC retailer the identical information in the identical area. Which one multiplies sooner relied on the machine, so select by entry sample.
- Construct in COO, sum duplicate positions, convert as soon as, and provides the pointer array n + 1 entries.
Incessantly Requested Questions
Conclusion
The three codecs maintain the identical matrix and differ solely in how they document positions, and that alternative decides each reminiscence and velocity. COO is the best to construct and the slowest to multiply. CSR makes the row-by-row product a sequential scan, and CSC does the identical for columns. The reminiscence adopted the formulation precisely: CSR took 0.015 of the dense measurement at 1 p.c density, 0.150 at 10 p.c and 0.750 at 50 p.c, and COO matched the dense measurement at 50 p.c. The CSR product was 105.79 occasions sooner than dense at 1 p.c and just one.99 occasions sooner at 50 p.c.
The information constructions hub lists the opposite constructions on this collection. In your personal code, select the format by entry sample first and reminiscence second, and change to a library as soon as matrices develop massive. Hold the pointer and index arithmetic underneath take a look at, as a result of the pitfalls present how a brief pointer array or a swapped index turns an accurate format right into a mistaken reply.
Supply Code and Checks
The packages on this web page are within the data-structures/sparse-matrix listing of the MYCPLUS C examples repository:
The examples construct and take a look at with CMake:
cmake -S . -B construct
cmake --build construct
ctest --test-dir construct --output-on-failure
The demo’s output is in contrast byte for byte with exams/anticipated/ordered.txt. The exams evaluate all three codecs with the dense matrix on fastened and random matrices. They examine that duplicates are summed, that each pointer array begins at 0, by no means decreases and ends on the nonzero depend, and that each one three merchandise match the dense product. Additionally they examine the fastened elements of each experiments’ output. The workflow runs the exams and pitfalls underneath AddressSanitizer and UndefinedBehaviorSanitizer, and the brief pointer array pitfall should produce its sanitizer abstract. No take a look at checks a time.
What I Verified
The instance listing comprises the take a look at packages and the captured runs. The desk states which system ran every examine.
| Examine | Ubuntu 24.04 (WSL2) | Home windows 11 (MSVC) |
|---|---|---|
| Construct and exams, GCC 13.3, C11 and C17 | Go (16 of 16 exams) | Not relevant |
| Construct and exams, Clang 18.1.3, C11 and C17 | Go (16 of 16 exams) | Not relevant |
Construct and exams, MSVC 19.44 /W4 /WX |
Not relevant | Go (16 of 16 exams) |
| AddressSanitizer and UndefinedBehaviorSanitizer, exams, demo and pitfalls | Go (16 of 16 exams) | Not relevant |
| 5 pitfalls, every caught by its examine or sanitizer abstract | Go (4 output checks, 1 AddressSanitizer abstract) | Not relevant |
| Reminiscence and timing experiments | Run, output above | Not run |
| Impartial rerun on a second Linux x86-64 machine (GCC 13.3, Clang 18.1.3) | Go (16 of 16 exams with each compilers and underneath the sanitizers, demo, reminiscence desk and 4 pitfall outputs an identical to the captures, timing form repeated) | Not relevant |
Not lined: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, different densities and matrix shapes, multithreaded merchandise, and timings on different machines past the one rerun famous above.

