fork download
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9.  
  10. namespace ConsoleApplication5
  11. {
  12. class Program
  13. {
  14. static long TestForeach()
  15. {
  16. var stopWatch = new Stopwatch();
  17. stopWatch.Start();
  18.  
  19. var list = new List<int>();
  20.  
  21. foreach (var i in Enumerable.Range(0, 10000))
  22. {
  23. list.Add(i);
  24. }
  25.  
  26. stopWatch.Stop();
  27. return stopWatch.ElapsedMilliseconds;
  28. }
  29.  
  30. static long TestParallelForEach()
  31. {
  32. var list = new List<int>();
  33. var stopWatch = new Stopwatch();
  34. stopWatch.Start();
  35. Parallel.ForEach(Enumerable.Range(0, 10000), new ParallelOptions() { MaxDegreeOfParallelism = 1000 }, i =>
  36. {
  37. lock (list)
  38. {
  39. list.Add(i);
  40. }
  41. });
  42.  
  43. stopWatch.Stop();
  44. return stopWatch.ElapsedMilliseconds;
  45. }
  46.  
  47. static long TestParallelForEachThreadSafeCollection()
  48. {
  49. var list = new BlockingCollection<int>();
  50. var stopWatch = new Stopwatch();
  51. stopWatch.Start();
  52. Parallel.ForEach(Enumerable.Range(0, 10000), new ParallelOptions() { MaxDegreeOfParallelism = 1000 }, i =>
  53. {
  54. list.Add(i);
  55. });
  56.  
  57. stopWatch.Stop();
  58. return stopWatch.ElapsedMilliseconds;
  59. }
  60.  
  61. static void Main(string[] args)
  62. {
  63. var times = new List<long>();
  64. Console.WriteLine("■TestForeach");
  65. Enumerable.Range(0, 1000).ToList().ForEach(i => times.Add(TestForeach()));
  66. //Enumerable.Range(0, 1000).ToList().ForEach(i => Console.WriteLine(times[i]));
  67. Console.WriteLine(times.Average());
  68.  
  69. times = new List<long>();
  70. Console.WriteLine("■TestParallelForEach");
  71. Enumerable.Range(0, 1000).ToList().ForEach(i => times.Add(TestParallelForEach()));
  72. //Enumerable.Range(0, 1000).ToList().ForEach(i => Console.WriteLine(times[i]));
  73. Console.WriteLine(times.Average());
  74.  
  75. times = new List<long>();
  76. Console.WriteLine("■TestParallelForEachThreadSafeCollection");
  77. Enumerable.Range(0, 1000).ToList().ForEach(i => times.Add(TestParallelForEachThreadSafeCollection()));
  78. //Enumerable.Range(0, 1000).ToList().ForEach(i => Console.WriteLine(times[i]));
  79. Console.WriteLine(times.Average());
  80. }
  81. }
  82. }
Time limit exceeded #stdin #stdout 5s 34720KB
stdin
Standard input is empty
stdout
■TestForeach
0.014
■TestParallelForEach
1.448
■TestParallelForEachThreadSafeCollection
3.032