Skip to content

Instantly share code, notes, and snippets.

@aholmes
Created July 15, 2016 16:00
Show Gist options
  • Save aholmes/35301d40d1a371e7625ab12fec2c046e to your computer and use it in GitHub Desktop.
Save aholmes/35301d40d1a371e7625ab12fec2c046e to your computer and use it in GitHub Desktop.
A comparison of performance between async/sync in C#
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace AsyncPerf
{
class Program
{
const int MAXRUNS = 10000000;
const int BYTEARRAYSIZE = 1000;
static MemoryStream ms = new MemoryStream();
static byte[] bytes = new byte[BYTEARRAYSIZE];
static void Main(string[] args)
{
var s = new Stopwatch();
s.Start();
for(var i = 0; i < MAXRUNS; i++)
{
Foo().Wait();
}
s.Stop();
var asyncElapsed = s.Elapsed;
s.Restart();
for(var i = 0; i < MAXRUNS; i++)
{
Bar();
}
s.Stop();
var syncElapsed = s.Elapsed;
Console.WriteLine("Async: {0}", asyncElapsed);
Console.WriteLine(" Sync: {0}", syncElapsed);
Console.WriteLine(" Diff: {0}", asyncElapsed - syncElapsed);
Console.ReadLine();
}
static async Task Foo()
{
ms.Seek(0, SeekOrigin.Begin);
await ms.WriteAsync(bytes, 0, BYTEARRAYSIZE);
}
static void Bar()
{
ms.Seek(0, SeekOrigin.Begin);
ms.Write(bytes, 0, BYTEARRAYSIZE);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment