fork download
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Diagnostics.Contracts;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6.  
  7. namespace BenchApp
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. double[] a = new double[16 * 1024 * 1024];
  14. Random rnd = new Random(0);
  15. for (int i = 0; i < a.Length; i++)
  16. {
  17. a[i] = rnd.NextDouble() * rnd.Next(1000);
  18. }
  19. var etalonSum = Enumerable.Sum(a);
  20.  
  21. var anothersum = a.Sum();
  22. Console.WriteLine(etalonSum);
  23. Console.WriteLine(anothersum);
  24. }
  25. }
  26.  
  27. public static class Test
  28. {
  29. [Pure]
  30. public static double Sum(this double[] source)
  31. {
  32. if (source.Length < Constants.SingleThreadExecutionThreshold)
  33. return Sum(source, 0, source.Length);
  34. double result = 0;
  35. object syncRoot = new object();
  36. Parallel.ForEach(Partitioner.Create(0, source.Length),
  37. () => (double)0,
  38. (range, state, sum) => Sum(source, range.Item1, range.Item2),
  39. x =>
  40. {
  41. lock (syncRoot)
  42. result += x;
  43. });
  44.  
  45. return result;
  46. }
  47. [Pure]
  48. private static double Sum(this double[] source, int startIndex, int endIndex)
  49. {
  50. double sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0;
  51. checked
  52. {
  53. int i;
  54. for (i = startIndex; i < endIndex - Constants.Step + 1; i += Constants.Step)
  55. {
  56. sum1 += source[i];
  57. sum2 += source[i + 1];
  58. sum3 += source[i + 2];
  59. sum4 += source[i + 3];
  60. }
  61. if (i == source.Length)
  62. return ((sum1 + sum2) + (sum3 + sum4));
  63. if (i == source.Length - 1)
  64. return ((sum1 + sum2) + (sum3 + sum4) + source[i]);
  65. if (i == source.Length - 2)
  66. return ((sum1 + sum2) + (sum3 + sum4) + (source[i] + source[i + 1]));
  67. return ((sum1 + sum2) + (sum3 + sum4) + (source[i] + source[i + 1] + source[i + 2]));
  68. }
  69. }
  70.  
  71. internal static class Constants
  72. {
  73. public const int Step = 4;
  74. public const int SingleThreadExecutionThreshold = 1024;
  75. }
  76. }
  77. }
Success #stdin #stdout 2.3s 27352KB
stdin
Standard input is empty
stdout
4188981720.25181
349297181.322729