使用c#中的线程用随机数填充数组
c#
所以正如在 tile 中所说,我正在尝试使用 16 个(在我的情况下)线程用随机数填充一个字节数组,现在使用一个线程填充一个包含 500000000 个字节的数组大约需要六秒半的时间,所以逻辑上说,使用 16 个线程至少会快 10 倍,但后来我尝试这样做,花了 15 秒来填充它,我所做的是给每个线程一个段来填充相同的数组
这是代码:
static byte[] nums2 = new byte[500000000];
static Random rnd = new Random(123);
static void fill()
{
for (int i = 0; i < nums.Length; i++)
nums[i] = (byte)rnd.Next(10);
}
static void fillPart(object ID)
{
var part = nums2.Length / Environment.ProcessorCount;
int baseN = (int)ID * part;
for (int i = baseN; i < baseN + part; i++)
nums2[i] = (byte)rnd.Next(10);
Console.WriteLine("Done! " + ID);
}
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
watch.Start();
fill();
watch.Stop();
Console.WriteLine("it took " + watch.Elapsed);
Console.WriteLine();
watch.Reset();
watch.Start();
Thread[] threads = new Thread[Environment.ProcessorCount];
for (int i = 0; i < Environment.ProcessorCount; i++)
{
threads[i] = new Thread(fillPart);
threads[i].Start(i);
}
for(int i = 0; i < Environment.ProcessorCount; i++)
threads[i].Join();
watch.Stop();
Console.WriteLine("it took " + watch.Elapsed);
}
}```
would like to understand why is it took 15 seconds or maybe what I did wrong
回答
如果是我,我只会:
byte[] nums = new byte[500000000];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(nums);
并完成它。
如果你真的想要线程:
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
var dop = 8;
var batchSize = 500000000 / dop;
var bigBytes = Enumerable.Range(0, dop).AsParallel().SelectMany(t => {
var bytes = new byte[batchSize];
rng.GetBytes(bytes); //This *IS* thread-safe
return bytes;
}).ToArray();
但我怀疑花整理成一个新的数组的时候SelectMany
,随后ToArray
可能使这种较昂贵,单一线程的方法。