Advertisement
Guest User

Dan Tao

a guest
Jan 30th, 2011
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3.  
  4. namespace ArrayAllocationTest
  5. {
  6.     class Program
  7.     {
  8.         const int N = 5000;
  9.         const int SmallSize = 10;
  10.         const int MediumSize = 10000;
  11.         const int LargeSize = 10000000;
  12.  
  13.         static void Main(string[] args)
  14.         {
  15.             int[] array = null;
  16.  
  17.             Console.WriteLine("Testing small ({0}) array allocation...", SmallSize);
  18.             TimeSpan smallArrayTime = TimeAllocations(ref array, SmallSize, N);
  19.  
  20.             Console.WriteLine("Testing medium ({0}) array allocations...", MediumSize);
  21.             TimeSpan mediumArrayTime = TimeAllocations(ref array, MediumSize, N);
  22.  
  23.             Console.WriteLine("Testing large ({0}) array allocation...", LargeSize);
  24.             TimeSpan largeArrayTime = TimeAllocations(ref array, LargeSize, N);
  25.  
  26.             Console.WriteLine("Small: {0} ms", smallArrayTime.TotalMilliseconds);
  27.             Console.WriteLine("Medium: {0} ms", mediumArrayTime.TotalMilliseconds);
  28.             Console.WriteLine("Large: {0} ms", largeArrayTime.TotalMilliseconds);
  29.  
  30.             Console.ReadLine();
  31.         }
  32.  
  33.         static TimeSpan TimeAllocations<T>(ref T[] array, int size, int count)
  34.         {
  35.             long ticks = 0L;
  36.  
  37.             for (int i = 0; i < count; ++i)
  38.             {
  39.                 ticks += TimeAllocation(ref array, size).Ticks;
  40.             }
  41.  
  42.             return TimeSpan.FromTicks(ticks);
  43.         }
  44.  
  45.         static TimeSpan TimeAllocation<T>(ref T[] array, int size)
  46.         {
  47.             GC.Collect();
  48.  
  49.             Stopwatch stopwatch = Stopwatch.StartNew();
  50.             array = new T[size];
  51.             stopwatch.Stop();
  52.  
  53.             return stopwatch.Elapsed;
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement