多线程

专注于多线程的开发与研究

导航

初次接触并行运算

Posted on 2013-04-15 22:30  threads  阅读(240)  评论(0)    收藏  举报

初次接触并行运算,感觉太强大了。

从最开始的Parallel.Invoke到现在的Parallel.For以及Parallel.Foreach,一步一步都看到了希望。。。

源码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 using System.Diagnostics;
 8 using System.Security.Cryptography;
 9 using System.Collections.Concurrent;
10 
11 namespace ConsoleApplication1
12 {
13     class Program
14     {
15         private const int NUM_AES_KEYS = 800000;
16         static void Main(string[] args)
17         {
18             GenerateAESKeys();
19             GenerateAESKeys1();
20             ParallelPartitionGenerateAESKeys();
21             Console.ReadLine();
22         }
23         private static void GenerateAESKeys()
24         {
25             Stopwatch sw = Stopwatch.StartNew();
26             var aesM = new AesManaged();
27             for (int i = 1; i <= NUM_AES_KEYS; i++)
28             {
29                 aesM.GenerateKey();
30                 byte[] result = aesM.Key;
31                 string hexString = Convert.ToString(result);
32             }
33             Console.WriteLine("串行用时:" + Convert.ToInt64(sw.Elapsed.TotalMilliseconds));
34         }
35         private static void GenerateAESKeys1()
36         {
37             Stopwatch sw = Stopwatch.StartNew();
38             Parallel.For(1, NUM_AES_KEYS + 1, (int i) =>
39                 {
40                     var aesM = new AesManaged();
41                     byte[] result = aesM.Key;
42                     string hexString = Convert.ToString(result);
43                 });
44             Console.WriteLine("Parallel.For并行用时:" + Convert.ToInt64(sw.Elapsed.TotalMilliseconds));
45         }
46         private static void ParallelPartitionGenerateAESKeys()
47         {
48             Stopwatch sw = Stopwatch.StartNew();
49             Parallel.ForEach(Partitioner.Create(1, NUM_AES_KEYS + 1), range =>
50                 {
51                     var aesM = new AesManaged();
52                     for (int i = range.Item1; i < range.Item2; i++)
53                     {
54                         aesM.GenerateKey();
55                         byte[] result = aesM.Key;
56                         string hexString = Convert.ToString(result);
57                     }
58                 });
59             Console.WriteLine("Parallel.ForEach并行用时:" + Convert.ToInt64(sw.Elapsed.TotalMilliseconds));
60         }
61     }
62 }

 

 

运行结果:

1 串行用时:1982
2 Parallel.For并行用时:509
3 Parallel.ForEach并行用时:458

 

联系Email:ha666@ha666.com