Advertisement
Guest User

unsafe perf

a guest
Sep 25th, 2011
693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.69 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace UnsafePerformance
  9. {
  10.     class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             int bufferSize = 8000;
  15.             int numberOfIterations = 10000;
  16.  
  17.             byte[] buf = new byte[bufferSize];
  18.             for (int i2 = 0; i2 < bufferSize; i2++) buf[i2] = (byte)(i2 % 256);
  19.             Stopwatch sw = new Stopwatch();
  20.  
  21.             int i = 0;
  22.             int cnt = 0;
  23.  
  24.             while (true)
  25.             {
  26.                 cnt = 0;
  27.                 sw.Restart();
  28.                 for (i = 0; i < numberOfIterations; i++)
  29.                     for (int j = 0; j < buf.Length; j++) cnt += buf[j];
  30.                 sw.Stop();
  31.                 Console.WriteLine(sw.Elapsed);
  32.  
  33.                 unsafe
  34.                 {
  35.                     cnt = 0;
  36.                     sw.Restart();
  37.                     for (i = 0; i < numberOfIterations; i++)
  38.                         for (int j = 0; j < buf.Length; j++) cnt += buf[j];
  39.                     sw.Stop();
  40.                     Console.WriteLine(sw.Elapsed);
  41.  
  42.                     fixed (byte* ptr = buf)
  43.                     {
  44.                         cnt = 0;
  45.                         sw.Restart();
  46.                         for (i = 0; i < numberOfIterations; i++)
  47.                             for (byte* j = ptr, lim = ptr + bufferSize; j < lim; j++) cnt += *j;
  48.                         sw.Stop();
  49.                         Console.WriteLine(sw.Elapsed);
  50.                     }
  51.  
  52.                 }
  53.  
  54.                 Console.ReadLine();
  55.             }
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement