如何创建大型整数数组来测试 LongCount
本文关键字:数组 整数 测试 LongCount 大型 何创建 创建 | 更新日期: 2023-09-27 17:56:08
我想分配一个大的整数数组来测试LongCount运算符。LongCount 运算符在以下情况下使用:
您希望结果大于最大值。
因此,为了准备我的测试,我想分配一个比Int32.MaxValue
大一点的整数数组:
Int64[] arr = new Int64[Int32.MaxValue + 10UL];
但这抛出了一个OverflowException
.
我想做的是这样的:
Int64[] arr = new Int64[Int32.MaxValue + 10UL];
var res = arr.LongCount();
然后期望res
2147483657
(这是Int32.MaxValue + 10
)。
我该怎么做?
您可以编写自己的列表实现来存储多个数组并将它们链接在一起(或者很可能在某个地方已经有一个更好的数组..)。映射你的巨大ulong
int 两个Int32
索引到达那里,在其上实现 IEnumerable
接口,然后进行测试。
ulong listSize = Int32.MaxValue + 10UL;
BigList<bool> myList = new BigList<bool>(listSize);
Debug.Assert(myList.LongCount() == (long)listSize);
Console.ReadKey();
示例实现..
public class BigList<T> : IEnumerable<T>
{
private List<T[]> _storage = new List<T[]>();
private const int _maxStorageArraySize = 1000;
public ulong Capacity { get; private set; }
public BigList(ulong capacity)
{
_storage = new List<T[]>();
Capacity = capacity;
int arraysRequired = (int)Math.Ceiling((double)capacity / (double)_maxStorageArraySize);
int lastArraySize = (int)(capacity % (ulong)_maxStorageArraySize);
for (int i = 0; i < arraysRequired; i++)
_storage.Add(new T[(i + 1) < arraysRequired ? _maxStorageArraySize : lastArraySize]);
}
public T this[ulong idx]
{
get
{
int arrayIdx = (int)(idx / (ulong)_maxStorageArraySize);
int arrayOff = (int)(idx % (ulong)_maxStorageArraySize);
return _storage[arrayIdx][arrayOff];
}
set
{
int arrayIdx = (int)(idx / (ulong)_maxStorageArraySize);
int arrayOff = (int)(idx % (ulong)_maxStorageArraySize);
_storage[arrayIdx][arrayOff] = value;
}
}
public class BigListEnumerator : IEnumerator<T>
{
private BigList<T> _bigList;
private ulong _idx;
public BigListEnumerator(BigList<T> bigList)
{
_bigList = bigList;
}
public T Current
{
get { return _bigList[_idx]; }
}
public void Dispose()
{
_bigList = null;
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
return _idx++ < _bigList.Capacity;
}
public void Reset()
{
_idx = 0;
}
}
public IEnumerator<T> GetEnumerator()
{
return new BigListEnumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new BigListEnumerator(this);
}
}
你不需要数组,也不应该使用数组。没有必要将 2GB 的内存专用于此测试(带有 byte[]
)。这就是它所需要的一切:
var items = Enumerable.Range(0, int.MaxValue).Concat(Enumerable.Range(0, 10));
使用它作为源。或者编写您自己的 RangeLong
方法,该方法由一个跨长变量的 for 循环组成。这将更快,因为项目通过的迭代器更少。在这种数量的项目下,性能成为一个问题。
问题是数组可以容纳的最大大小是System.Int32.MaxValue
,当您要创建一个元素多于System.Int32.MaxValue
的数组时,它将抛出OverflowException