Created
July 15, 2016 16:00
-
-
Save aholmes/35301d40d1a371e7625ab12fec2c046e to your computer and use it in GitHub Desktop.
A comparison of performance between async/sync in C#
This file contains hidden or 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.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