Skip to content

Commit e01a438

Browse files
author
Release Manager
committed
gh-37375: Speed up square matrix times vector over GF(2) When doing a matrix-times-vector multiplication over F_2, there is some inefficiency caused by calling `VectorSpace` to create a parent for the result. This becomes noticeable when repeatedly multiplying small matrices. When the dimensions are all the same, this can be improved by using the parent of the vector also as the parent for the result. Before: ``` sage: A = random_matrix(GF(2),10,10) sage: v0 = vector(random_matrix(GF(2),10,1)) sage: %timeit A*v0 2.26 µs ± 4.57 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) ``` After: ``` sage: A = random_matrix(GF(2),10,10) sage: v0 = vector(random_matrix(GF(2),10,1)) sage: %timeit A*v0 981 ns ± 9.57 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each) ``` URL: #37375 Reported by: kedlaya Reviewer(s): Lorenz Panny
2 parents 193e49d + 86a75ae commit e01a438

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

src/sage/matrix/matrix_mod2_dense.pyx

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -595,14 +595,27 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse
595595
sage: v = vector(GF(2), 0)
596596
sage: m * v
597597
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
598+
599+
Add a test involving a nonsquare matrix::
600+
601+
sage: A = random_matrix(GF(2),10^4,10^3)
602+
sage: v0 = random_matrix(GF(2),10^3,1)
603+
sage: v1 = v0.column(0)
604+
sage: r0 = A*v0
605+
sage: r1 = A*v1
606+
sage: r0.column(0) == r1
607+
True
598608
"""
599609
cdef mzd_t *tmp
600-
global VectorSpace
601-
if VectorSpace is None:
602-
from sage.modules.free_module import VectorSpace
603-
VS = VectorSpace(self._base_ring, self._nrows)
604-
if not isinstance(v, Vector_mod2_dense):
605-
v = VS(v)
610+
if self._nrows == self._ncols and isinstance(v, Vector_mod2_dense):
611+
VS = v.parent()
612+
else:
613+
global VectorSpace
614+
if VectorSpace is None:
615+
from sage.modules.free_module import VectorSpace
616+
VS = VectorSpace(self._base_ring, self._nrows)
617+
if not isinstance(v, Vector_mod2_dense):
618+
v = VS(v)
606619
if self.ncols() != v.degree():
607620
raise ArithmeticError("number of columns of matrix must equal degree of vector")
608621

0 commit comments

Comments
 (0)