我一直在使用Vector进行实验来使用HW来平行整数运算。有什么办法来启用向量操作溢出检查?我可以使用Vector来执行算术运算吗<T>
一个示例是将两列(等长阵列)的整数相加在一起。这里c=a+b
意味着c[0] = a[0] + b[0]
,c[1] = a[1] + b[1]
等
我想我可以做这样的事情:
overflow[i] = b[i] >= 0 ? c[i] < a[i] : c[i] >= a[i];
但这(分支)可能会比净的自动溢出检查较慢,并且可能否定的性能优势使用Vector<T>
。
我们还希望优化我们最常用的操作:乘法,减法,以较小程度的整数除法。
编辑:我想到了这一点,并想出了这个,这是未经检查的载体添加速度的2.5倍。看起来像很多额外的开销。
public Vector<int> Calc(Vector<int> a, Vector<int> b)
{
var result = a + b;
var overflowFlag = Vector.GreaterThan(b, Vector<int>.Zero) * Vector.LessThan(result,a)
+ Vector.LessThan(b,Vector<int>.Zero) * Vector.GreaterThan(result, a);
// It makes no sense to add the flags to the result, but haven't decided what to do with them yet,
// and don't want the compiler to optimise the overflow calculation away
return result + overflowFlag;
}
时序:(4K迭代添加一对100K阵列)
- 普通添加:618ms
- 普通经过添加:1092ms
- 向量添加:208ms
- 矢量已加入:536ms
不是,但你可以自己检查它当然。在更多的背景下,我可以提供更有针对性的建议。 – harold
@哈罗德 - 我添加了一点进一步的背景。有没有一种确定溢出是否发生的有效方法? – Rob
你不需要分支(实际上你不能),你可以使用ConditionalSelect。乘法是棘手的,没有扩大和扩大是讨厌的,我会考虑它。稍后我会回来更正确地回答 – harold