Skip to content

Instantly share code, notes, and snippets.

@tejacques
Last active December 19, 2015 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tejacques/5941069 to your computer and use it in GitHub Desktop.
Save tejacques/5941069 to your computer and use it in GitHub Desktop.
Test the execution time of task wrapping / waiting vs. AsyncBrdige.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using AsyncBridge;
using System.Diagnostics;
namespace AsyncTests
{
[TestFixture]
public class TestRuntimes
{
int loops;
[TestFixtureSetUp]
public void SetUp()
{
// Warm up the JIT
Console.WriteLine("JIT Warmup: 1 loop");
loops = 1;
TestTaskWrapper();
TestAsyncBridge();
loops = 100;
Console.WriteLine("Actual Results: {0} loops", loops);
}
[Test]
public void TestTaskWrapper()
{
Stopwatch sw = new Stopwatch();
sw.Start();
List<Task<string>> tasks = new List<Task<string>>(loops);
for (int i = 0; i < loops; i++)
{
tasks.Add(TaskWrapper(() => AsyncString().Result));
}
StringBuilder sb = new StringBuilder(loops);
for (int i = 0; i < loops; i++)
{
sb.Append(tasks[i].Result);
}
sw.Stop();
Console.WriteLine("TestTaskWrapper: " + sw.Elapsed.TotalMilliseconds + " ms");
}
[Test]
public void TestAsyncBridge()
{
Stopwatch sw = new Stopwatch();
sw.Start();
List<string> strings = new List<string>(loops);
using (var A = AsyncHelper.Wait)
{
for (int i = 0; i < loops; i++)
{
A.Run(AsyncString(), task => strings.Add(task.Result));
}
}
sw.Stop();
Console.WriteLine("TestAsyncBridge: " + sw.Elapsed.TotalMilliseconds + " ms");
}
private async Task<string> AsyncString()
{
await Task.Yield();
return "AsyncString";
}
private Task<T> TaskWrapper<T>(Func<T> func)
{
var task = new Task<T>(() => func());
task.Start();
return task;
}
}
}
@tejacques
Copy link
Author

Here is the output from running this test:

JIT Warmup: 1 loop
TestTaskWrapper: 2.4021 ms
TestAsyncBridge: 3.3756 ms
Actual Results: 100 loops
TestAsyncBridge: 0.3872 ms
TestTaskWrapper: 83406.3203 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment