我正在开发一个应用程序,它可以扫描数千个结构的副本; ~1 GB RAM.速度很重要.
ParallelScan(_from, _to); //In a new thread
Run Code Online (Sandbox Code Playgroud)
我手动调整线程数:
if (myStructs.Count == 0) { threads = 0; }
else if (myStructs.Count < 1 * Number.Thousand) { threads = 1; }
else if (myStructs.Count < 3 * Number.Thousand) { threads = 2; }
else if (myStructs.Count < 5 * Number.Thousand) { threads = 4; }
else if (myStructs.Count < 10 * Number.Thousand) { threads = 8; }
else if (myStructs.Count < 20 * Number.Thousand) { threads = 12; }
else if (myStructs.Count < 30 * Number.Thousand) { threads = 20; }
else if (myStructs.Count < 50 * Number.Thousand) { threads = 30; }
else threads = 40;
Run Code Online (Sandbox Code Playgroud)
我只是从头开始编写它,我需要为另一个CPU等修改它.我想我可以编写一个更智能的代码,如果CPU现在可用,它会动态启动一个新线程:
有没有人认为"我做过类似的事"或"我有更好的主意"?
更新:解决方案
Parallel.For(0, myStructs.Count - 1, (x) =>
{
ParallelScan(x, x); // Will be ParallelScan(x);
});
Run Code Online (Sandbox Code Playgroud)
我确实修改了很多代码.谢谢大家!
更新2:结果
扫描10K模板的时间
标准答案:使用任务(TPL),而不是线程.任务需要Fx4.
您的ParallelScan可以使用Parallel.Foreach( ... )或PLINQ(.AsParallel()).
TPL框架包括一个调度程序,并ForEach()使用分区程序来适应CPU核心和负载.您的问题最有可能通过标准组件解决,但您可以编写自定义调度程序和分区程序.