A quick app to test the latency overhead of asynchronous calls in .NET.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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