Advertisement
Guest User

Untitled

a guest
Aug 15th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.27 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Threading;
  6.  
  7.  
  8. namespace Bench
  9. {
  10.     class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             var random = new Random();
  15.  
  16.             var list = Enumerable.Range(0, 1000000).Select(number => random.NextDouble() + number);
  17.  
  18.             var result = new[] { GetTime(list, YobaLinqTest),
  19.                                  GetTime(list, ParsingDoubleNewTest),
  20.                                  GetTime(list, ExtensionDoubleTest)
  21.                                };
  22.  
  23.             foreach(var time in result)
  24.             {
  25.                 Console.WriteLine(time);
  26.             }
  27.            
  28.  
  29.         }
  30.  
  31.         static TimeSpan GetTime(IEnumerable<double> collection, Action<double> action)
  32.         {
  33.             var bench = new Stopwatch();
  34.  
  35.             bench.Start();
  36.             foreach (var number in collection)
  37.             {
  38.                 action(number);
  39.             }
  40.             bench.Stop();
  41.  
  42.  
  43.             return bench.Elapsed;
  44.         }
  45.  
  46.         static void YobaLinqTest(double value)
  47.         {
  48.             value.ToString().Split(new[] { ',', '.' }).Select(number => Convert.ToInt64(number));
  49.         }
  50.  
  51.         static void ParsingDoubleNewTest(double value)
  52.         {
  53.             string s = Math.Abs(value).ToString();
  54.             int index = s.IndexOf(Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);
  55.  
  56.             long integer = index != -1 ? Convert.ToInt64(s.Substring(0, index)) : Convert.ToInt32(s);
  57.             long fractional = index != -1 ? Convert.ToInt64(s.Substring(index + 1)) : 0;
  58.         }
  59.  
  60.         static void ExtensionDoubleTest(double value)
  61.         {
  62.             value.IntPart();
  63.             value.FractPart();
  64.         }
  65.  
  66.     }
  67. }
  68.  
  69.  
  70. public static class DoubleExtentions
  71. {
  72.     public static long IntPart(this double value)
  73.     {
  74.         return (long)Math.Truncate(value);
  75.     }
  76.  
  77.     public static long FractPart(this double value)
  78.     {
  79.         var str = value.ToString();
  80.         int sepIndex = str.LastIndexOf(Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);
  81.         return (sepIndex != -1) ? long.Parse(str.Substring(sepIndex + 1)) : 0;
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement