我以为我会分享几个片段,如果有人可以指出我的paralle代码运行速度比线程代码慢.还试图运行相同的比较找到素数,发现并行代码完成比线程代码晚.
public class ThreadFactory{ int workersCount; private List<Thread> threads = new List<Thread>(); public ThreadFactory(int threadCount,int workCount,Action<int,int,string> action) { workersCount = threadCount; int totalWorkLoad = workCount; int workLoad = totalWorkLoad / workersCount; int extraLoad = totalWorkLoad % workersCount; for (int i = 0; i < workersCount; i++) { int min,max; if (i < (workersCount - 1)) { min = (i * workLoad); max = ((i * workLoad) + workLoad - 1); } else { min = (i * workLoad); max = (i * workLoad) + (workLoad - 1 + extraLoad); } string name = "Working Thread#" + i; Thread worker = new Thread(() => { action(min,max,name); }); worker.name = name; threads.Add(worker); } } public voID StartWorking() { foreach (Thread thread in threads) { thread.Start(); } foreach (Thread thread in threads) { thread.Join(); } }}
这是程序:
Stopwatch watch = new Stopwatch();watch.Start();int path = 1;List<int> numbers = new List<int>(Enumerable.Range(0,10000));if (path == 1){ Parallel.ForEach(numbers,x => { Console.Writeline(x); Thread.Sleep(1); });}else{ ThreadFactory workers = new ThreadFactory(10,numbers.Count,(min,text) => { for (int i = min; i <= max; i++) { Console.Writeline(numbers[i]); Thread.Sleep(1); } }); workers.StartWorking();}watch.Stop();Console.Writeline(watch.Elapsed.TotalSeconds.ToString());Console.Readline();
更新:
考虑到锁定:我尝试了以下代码段.同样的结果,Parallel似乎完成得比较慢.
path = 1;
cIEling = 10000000;
List<int> numbers = new List<int>(); if (path == 1) { Parallel.For(0,cIEling,x => { lock (numbers) { numbers.Add(x); } }); } else { ThreadFactory workers = new ThreadFactory(10,text) => { for (int i = min; i <= max; i++) { lock (numbers) { numbers.Add(i); } } }); workers.StartWorking(); }
更新2:
只是一个快速更新,我的机器有四核处理器.所以Parallel可以有4个内核.
两种方法的工作原理相同,但是如果您先创建所有线程,则可以将Parallels分配给Parallel.For使用任务池来添加一些移动开销.
总结以上是内存溢出为你收集整理的C#并行线程代码性能全部内容,希望文章能够帮你解决C#并行线程代码性能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)