Skip to content

Instantly share code, notes, and snippets.

@rionmonster
Created April 6, 2016 16:14
Show Gist options
  • Save rionmonster/ea942e541b787a49451ab407e990e3ce to your computer and use it in GitHub Desktop.
Save rionmonster/ea942e541b787a49451ab407e990e3ce to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace ExampleConsole
{
class Program
{
static void Main(string[] args)
{
// Store averages
var loops = new List<long>();
var buffers = new List<long>();
// Create a stopwatch for performance testing
var stopwatch = new Stopwatch();
// Test content
var data = GetTestingBytes();
for(int i = 0; i < 1000; i++)
{
// Looping Test
using (var s1 = new MemoryStream())
{
stopwatch.Start();
foreach (var item in data)
{
s1.WriteByte(item);
}
stopwatch.Stop();
loops.Add(stopwatch.ElapsedTicks);
}
// Buffered Test
using (var s2 = new MemoryStream())
{
stopwatch.Start();
s2.Write(data, 0, data.Length);
stopwatch.Stop();
buffers.Add(stopwatch.ElapsedTicks);
}
}
// Get averages
var avgLoop = new TimeSpan((long)loops.Average());
var avgBuffer = new TimeSpan((long)buffers.Average());
Console.WriteLine($"Average Loop Test: {avgLoop}");
Console.WriteLine($"Average Buffer Test: {avgBuffer}");
Console.Read();
}
static byte[] GetTestingBytes()
{
var str = String.Join(",", Enumerable.Range(0, 1000).Select(x => Guid.NewGuid()).ToArray());
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment