为什么想要了解并行程序的写法,源自上学期间有一个算法需要处理很多的地震道记录,在处理地震道的时候各道的数据是不关联的,
因此是两个for循环X,Y方向的地震道数据,然后计算,自然速度就慢了。
那么如果对于计算密集型的处理程序,并行计算就成了好的选择。
在C#中的三种写法:参考资料
static void Main(string[] args) { //方法1 Parallel.For(1, 11, x => { Console.WriteLine(x); }); Console.WriteLine("-------"); //方法2 var nums = Enumerable.Range(20, 30); Parallel.ForEach(nums, x => { Console.WriteLine(x); }); Console.WriteLine("-------"); //方法3 Parallel.Invoke( new Action(func1),//1 new Action(func1),//2 new Action(func1),//3 new Action(func1),//4 new Action(func1),//5 new Action(func1),//6 new Action(func1),//7 new Action(func1)//8 ); //Console.ReadKey(); } public static void func1() { long x = (long)Math.Pow(10, 10); for (int i = 0; i < x; i++) { Console.WriteLine("内部线程" + i); } }
这里比较灵活的写法是方法三:
使用的委托调用需要处理的函数,fuc1是一个计算耗时函数
我在例子中调用了8个函数,我的电脑是I7-7700
是八核,跑起来程序是直接CPU100%
如果注释掉其中的四行代码,只跑4个耗时函数
那么CPU的使用是50%
相比于单线程计算,并行确实能提高时间效率。
但是也要注意,不要执行太多耗时任务,否则对计算机压力太大。
End
原文:https://www.cnblogs.com/LeeSki/p/12188200.html