Skip to content

Instantly share code, notes, and snippets.

@nzbart
Last active December 19, 2015 08:38
Show Gist options
  • Save nzbart/5926566 to your computer and use it in GitHub Desktop.
Save nzbart/5926566 to your computer and use it in GitHub Desktop.
A quick app to test the latency overhead of asynchronous calls in .NET.
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace ConsoleApplication6
{
class Program
{
static void Main()
{
const int count = 1000000;
var filePath = Path.GetTempFileName();
File.WriteAllBytes(filePath, new byte[count]);
Console.WriteLine("File length: {0} bytes.", new FileInfo(filePath).Length);
RunTimedOperation(filePath, "Preload", (fs, b) => fs.Read(b, 0, 1), 100);
RunTimedOperation(filePath, "Asynchronous", (fs, b) => fs.ReadAsync(b, 0, 1).Wait(), count);
RunTimedOperation(filePath, "Synchronous", (fs, b) => fs.Read(b, 0, 1), count);
}
static void RunTimedOperation(string filePath, string operationName, Action<FileStream, byte[]> operation, int count)
{
Console.WriteLine("Running {0} loops of {1}...", count, operationName);
var timer = Stopwatch.StartNew();
using (var file = File.OpenRead(filePath))
{
var buffer = new byte[1];
for (int i = 0; i != count; ++i)
{
operation(file, buffer);
}
}
long elapsedMilliseconds = timer.ElapsedMilliseconds;
Console.WriteLine("Done in {0} ms.", elapsedMilliseconds);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment