2

我有一个矩阵说A的大小M×N。我必须调用整个矩阵中的每列相同的函数。到目前为止,我一直在中提取每一列并通过迭代列调用该函数直到N。即(列数)加速一次又一次调用相同函数的代码

是否有任何更好/更快的方式来做到这一点?

任何帮助表示赞赏。谢谢

+0

你有没有考虑调换,然后刚好路过的行?由于更高的缓存利用率,您可能会获得更高的性能,并且您将消除提取列所需的时间。但是,如果没有一些代码来看看其他瓶颈可能在哪里,那很难说。 – Alejandro

回答

1

如今,如果你能使用并行计算来提升性能。

CPU是多核/多线程。

您可以使用例如java 8流和并行计算。

例如

Matrix Vector Multiplication

@Test 
    2 public static void matrixVectorProduct() { 
    3  System.out.println("Matrix Vector multiplication"); 
    4  final int DIM = 5; 
    5   
    6  int [][]a = new int[DIM][DIM]; 
    7  int counter = 1; 
    8  for (int i = 0; i < a.length; i++) { 
    9   for (int j = 0; j < a[0].length; j++) { 
10    a[i][j] = counter++; 
11   } 
12  } 
13   
14  int []v = new int[DIM]; 
15  Arrays.fill(v, 5);   
16  int []c = new int[DIM]; 
17   
18  IntStream.range(0, c.length) 
19    .parallel() 
20    .forEach((i) -> { 
21     IntStream.range(0, a.length) 
22       .sequential() 
23       .forEach((j) -> { c[i] += v[j] * a[i][j]; }); 
24       }); 
25 
26   
27  int []expected = new int[]{75, 200, 325, 450, 575}; 
28  assertArrayEquals(expected, c); 
29   
30  System.out.println("Matrix-Vector product: " + Arrays.toString(c));   
31 } 
相关问题