fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4.  
  5. namespace ConsoleApplication18
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. var arr = new byte[100000000];
  12.  
  13. var sw = Stopwatch.StartNew();
  14. try
  15. {
  16. Console.WriteLine(arr.Single(i => i == 0));
  17. }
  18. catch (Exception)
  19. {
  20. sw.Stop();
  21. }
  22. finally
  23. {
  24. Console.WriteLine(sw.Elapsed);
  25. }
  26.  
  27.  
  28. var sw2 = Stopwatch.StartNew();
  29. try
  30. {
  31. Console.WriteLine(arr.MySingle(i => i == 0));
  32. }
  33. catch (Exception)
  34. {
  35. sw2.Stop();
  36. }
  37. finally
  38. {
  39. Console.WriteLine(sw2.Elapsed);
  40. }
  41.  
  42. Console.WriteLine("Difference = {0}", (double) sw.ElapsedTicks/sw2.ElapsedTicks);
  43.  
  44. }
  45. }
  46.  
  47. public static class LinqTester
  48. {
  49. public static TSource MySingle<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
  50. {
  51. if (source == null)
  52. throw new ArgumentNullException("source");
  53. if (predicate == null)
  54. throw new ArgumentNullException("predicate");
  55. TSource result = default(TSource);
  56. int count = 0;
  57. foreach (TSource value in source)
  58. {
  59. if (predicate(value))
  60. {
  61. checked { ++count; }
  62. if (count > 1)
  63. throw new Exception("MoreThanOneMatch");
  64. result = value;
  65. }
  66. }
  67. if (count == 0)
  68. throw new Exception("NoMatch");
  69. return result;
  70. }
  71.  
  72. public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
  73. {
  74. if (source == null)
  75. throw new ArgumentNullException("source");
  76. if (predicate == null)
  77. throw new ArgumentNullException("predicate");
  78. TSource source1 = default(TSource);
  79. long num = 0L;
  80. foreach (TSource source2 in source)
  81. {
  82. if (predicate(source2))
  83. {
  84. source1 = source2;
  85. checked { ++num; }
  86. }
  87. }
  88. switch (num)
  89. {
  90. case 0L:
  91. throw new Exception("NoMatch");
  92. case 1L:
  93. return source1;
  94. default:
  95. throw new Exception("MoreThanOneMatch");
  96. }
  97. }
  98. }
  99. }
  100.  
Success #stdin #stdout 3.85s 131776KB
stdin
Standard input is empty
stdout
00:00:03.7073841
00:00:00.0003348
Difference = 11073.4292114695