2016-02-11 41 views
5

我正在嘗試使用System.Numerics.Vector<T>documentation)。爲什麼Vector。計數是靜態的?

我寫了一個簡單的單元測試:

var v = new System.Numerics.Vector<double>(new double[] { 12, 13, 14 }); 
Assert.AreEqual(3, v.Count); 

但它給了我一個生成錯誤:

Member 'Vector.Count' cannot be accessed with an instance reference; qualify it with a type name instead

出乎我的意料,Vector<T>.Count是靜態的。

所以,我想:

var v = new System.Numerics.Vector<double>(new double[] { 12, 13, 14 }); 
Assert.AreEqual(3, Vector<double>.Count); 

現在的代碼生成,但單元測試失敗:

Assert.AreEqual failed. Expected:<3>. Actual:<2>.

這是怎麼回事?


調查,我發現:

Assert.AreEqual(2, Vector<double>.Count); 
Assert.AreEqual(4, Vector<float>.Count); 
Assert.AreEqual(4, Vector<int>.Count); 
Assert.AreEqual(2, Vector<long>.Count); 
+2

您的兩個片段是相同的。 – BoltClock

+0

@BoltClock謝謝修復。 –

+0

那麼,你正在發現爲什麼這個類沒有被添加到框架中。在Haswell或Broadwell處理器上,您獲得的價值也很可能是錯誤的,因爲它將使用AVX2提供的256位YMM寄存器,所以它應該是該值的兩倍。在桌子上留下2個perf,難以隱藏實現細節。 AVX-512即將推出:) –

回答

4

The documentation表明,這是由設計:

The count of a Vector instance is fixed, but its upper limit is CPU-register dependent.

其目的是爲了讓使用硬件功能矢量化操作,因而其容量是綁到你的CPU架構。

+3

來自MSDN的聲明只是讓事情更令IMO感到困惑,因爲措辭「Vector實例的計數」意味着Count實際上是一個實例成員。 – BoltClock

+1

感謝從我閱讀的頁面不明顯「返回存儲在向量中的元素的數量」。 https://msdn.microsoft.com/en-us/library/dn877911(v=vs.111).aspx –

+0

@BoltClock真的,它不是很清楚,它應該是。 – BartoszKP

2

向量可能有點混淆的類型。它是固定的預定義長度的集合。它是固定的,因爲它的長度總是== Vector<T>.Count。所以,如果你這樣做:

var v = new Vector<double>(new double[] { 12, 13, 14 }); 
Console.WriteLine(v); 

結果是...:

<12, 13> 

它只是刪除所有值在Vector<double>.Count這恰好是2的訣竅是Vector<T>.Count可以根據CPU架構的改變。

它實際上是相當低的水平原始,作爲描述說:

Represents a single vector of a specified numeric type that is suitable for low-level optimization of parallel algorithms.

相關問題