Last active
November 29, 2016 16:36
-
-
Save scionwest/8228cfbd0e9891db533fb5fa6537e712 to your computer and use it in GitHub Desktop.
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.Collections.Generic; | |
| using System.Diagnostics; | |
| using System.IO; | |
| using System.Linq; | |
| using System.Linq.Expressions; | |
| namespace CompiledActionDelegate | |
| { | |
| class Program | |
| { | |
| static Action<BinaryWriter> compiledAction = null; | |
| static Action<BinaryWriter> precompiledAction = new Action<BinaryWriter>(writer => writer.Write("Foo Bar")); | |
| static string Name { get; set; } = "Foo Bar"; | |
| static void Main(string[] args) | |
| { | |
| var watch = new Stopwatch(); | |
| int iterations = 1000000; | |
| var times = new List<long>(); | |
| for (int count = 0; count < iterations; count++) | |
| { | |
| watch.Start(); | |
| RunAction(precompiledAction); | |
| watch.Stop(); | |
| times.Add(watch.Elapsed.Ticks); | |
| watch.Reset(); | |
| } | |
| Console.WriteLine($"Average Action warmup time: {times.Average()} ticks over {times.Sum()} ticks."); | |
| CreateCompiledAction(writer => writer.Write("Foo Bar")); | |
| times.Clear(); | |
| for (int count = 0; count < iterations; count++) | |
| { | |
| watch.Start(); | |
| RunAction(precompiledAction); | |
| watch.Stop(); | |
| times.Add(watch.Elapsed.Ticks); | |
| watch.Reset(); | |
| } | |
| Console.WriteLine($"Average Action time: {times.Average()} ticks over {times.Sum()} ticks."); | |
| CreateCompiledAction(writer => writer.Write("Foo Bar")); | |
| times.Clear(); | |
| for (int count = 0; count < iterations; count++) | |
| { | |
| watch.Start(); | |
| RunCompiledAction(compiledAction); | |
| watch.Stop(); | |
| times.Add(watch.Elapsed.Ticks); | |
| watch.Reset(); | |
| } | |
| Console.WriteLine($"Average Action time: {times.Average()} ticks over {times.Sum()} ticks."); | |
| Console.ReadKey(); | |
| } | |
| static void RunAction(Action<BinaryWriter> callback) | |
| { | |
| using (var writer = new BinaryWriter(new MemoryStream())) | |
| { | |
| callback(writer); | |
| } | |
| } | |
| static void RunCompiledAction(Action<BinaryWriter> callback) | |
| { | |
| using (var writer = new BinaryWriter(new MemoryStream())) | |
| { | |
| callback(writer); | |
| } | |
| } | |
| static void CreateCompiledAction(Expression<Action<BinaryWriter>> exp) | |
| { | |
| compiledAction = exp.Compile(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment