矢量矩阵乘法顺序会影响性能吗? [英] Vector-Matrix multiplication order can affect performance?

查看:56
本文介绍了矢量矩阵乘法顺序会影响性能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是行优先与列优先的问题.这是一个与性能有关的计算问题的顺序,基于矩阵乘法的关联性质:A(BC)=(AB)C

This is not a row-major vs column-major question. This is an order of calculation question as pertaining to performance, based on the associative property of matrix multiplication: A(BC)=(AB)C

如果我有 2 个矩阵,AB,以及一个向量 v,我想将它们按特定顺序相乘,例如ABv,我可以做(AB)vA(Bv).

If I have 2 matrices, A and B, and a vector v and I want to multiply them all together in a certain order, for example ABv, I can do (AB)v or A(Bv).

我突然想到,以编程方式,如果我使用第二种方法并始终将矩阵与向量相乘,我可以通过更少的计算获得更好的性能.

It occurs to me, programmatically, that I get better performance from far fewer calculations if I use the second method and always multiply a matrix with a vector.

例如,如果我们正在处理 4x4 矩阵:

For example, if we are dealing with 4x4 matrices:

AB 16 个单独计算的结果,一个新矩阵,每个结果来自一个点积

AB results in 16 individual calculations, a new matrix, each result is from a dot product

Matrix*vector 产生 4 个计算,每个计算来自一个点积

Matrix*vector results in 4 calculations, each from a dot product

因此:

(AB)v 是 16+4 点积计算=20

(AB)v is 16+4 dot product calculations=20

A(Bv) 是两个矩阵向量乘积,或4+4点积计算=8

A(Bv) is two matrix-vector products, or 4+4 dot product calculations = 8

我的想法正确吗?这表明如果我每次都从向量开始,执行许多这样的向量矩阵表达式会显着提高性能吗?

Am I thinking correctly? This suggests that performing many many vector-matrix expressions like this will dramatically improve performance if I start with the vector each time?

因此构建一个基于 vector*matrix 从左到右计算顺序执行的矩阵库是有意义的(即使您选择使用列主要格式从右到左记号),因为将向量与矩阵乘积在图形中很常见.

Thus it would make sense to structure a matrix library that performs based on vector*matrix left-to-right calculation order (even if you choose to notate right-to-left with column-major formatting) since multiplying a vector with matrix products is very common in graphics.

推荐答案

在矩阵的单个操作和涉及的单个向量的有限上下文中,您和 tmyklebu 是正确的.但是,在实际应用之前,您通常需要了解更大的上下文.该问题围绕 AB 相对于 v 变化的频率变化的频率.如果 ABv 相比是相对静态的(它们不会经常变化),那么您最好预先计算 AB 并将其应用于 v 碰巧拥有的任何值.

Within the limited context of a single operation of the matrices and a single vector involved, you and tmyklebu have it right. However, there is usually a larger context you need to be aware of before you apply it in practice. That issue revolves around how often A and B change relative to how often v changes. If A and B are relatively static (they don't change very often) compared with v, you may be better off precomputing AB and applying it to whatever value v happens to have.

此外,在实践中,有一些几何图形由多个向量组成,可以通过首先计算 AB 然后将该转换应用于几何图形中的所有向量来更有效地转换和计算它们.

Furthermore, in practice, there is some geometry comprised of multiple vectors which can be more efficiently transformed and computed together by first computing AB and then applying that transformation to all of the vectors in the geometry.

这篇关于矢量矩阵乘法顺序会影响性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆