zoukankan      html  css  js  c++  java
  • C#并行编程之数据并行

    所谓的数据并行的条件是:

          1、拥有大量的数据。

          2、对数据的逻辑操作都是一致的。

          3、数据之间没有顺序依赖。

    运行并行编程可以充分的利用现在多核计算机的优势。记录代码如下:

     public class ParallerFor
        {
            public List<string> studentList;
    
            public ParallerFor() {
                this.studentList = new List<string>();
                for (int i = 0; i < 50; i++) {
                    this.studentList.Add("xiaochun"+i.ToString());
                }
            }
    
            public void ParallerTest() {
                var sw = Stopwatch.StartNew();
                foreach (string str in this.studentList) {
                    Console.WriteLine("this is sync "+str);
                    Thread.Sleep(800);
                }
                Console.WriteLine("运行时间:"+sw.Elapsed.ToString());
            }
    
            public void ParallerAsyncTest() {
                var sw = Stopwatch.StartNew();
                Action<int> ac = (i) => { Console.WriteLine("this is async " + this.studentList[i]); Thread.Sleep(800); };
                Parallel.For(0, this.studentList.Count,ac);//这里的0是指循环的起点
                Console.WriteLine("运行时间:" + sw.Elapsed.ToString());
            }
    
            public void ParallalForEachTest() {
                var sw = Stopwatch.StartNew();
                Action<string> ac = (str) => {
                        int num = int.Parse(str.Replace("xiaochun",string.Empty));
                        if (num > 10) {
                            Console.WriteLine(str);
                            Thread.Sleep(1000);
                        }
                };
                //限定最大并行数目
                ParallelOptions op = new ParallelOptions();
                op.MaxDegreeOfParallelism = 4;
                Parallel.ForEach(this.studentList,op,ac);
                //这里没有限定最大并行数目
                //Parallel.ForEach(this.studentList,ac);
            }
    
        }
  • 相关阅读:
    echarts onClick执行之前都要取消绑定一次
    echarts 打包完之后体积太大解决方案。
    saga处理多个loading最少0.5s
    SVN命令详解
    netfilter/iptables原理
    交换两个变量的值,不使用第三个变量的四种法方
    linux常用命令整理
    vi技巧
    linux进程管理的常用命令
    gcc常用命令
  • 原文地址:https://www.cnblogs.com/msql/p/6109459.html
Copyright © 2011-2022 走看看