kemnet
2/8/2014 - 8:42 PM

asyncScaleTest

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace AsyncTest
{
    class Program
    {
        public static int dummyTaskDelay = 1000;
        
        public static async Task DummyTask(int taskId, int delay) {
            await Task.Delay(delay);
        }

        public static async Task test(int n) {
            var tasks = Enumerable
                .Range(1, n)
                .Select(i =>
                        DummyTask(i, delay:dummyTaskDelay)
                );
            await Task.WhenAll(tasks);
        }

        public static long MeasureTime(Action f)
        {
            var sw = Stopwatch.StartNew();
            f();
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }
        
        static void Main(string[] args)
        {
            foreach (var tasksCount in new [] {1000, 10000, 100000, 1000000}) {
                var elapsedTime = MeasureTime( () => Task.WaitAll(new [] { test(tasksCount) }));

                Console.WriteLine( 
                    "{0} tasks completed in {1} ms; overhead {2} ms; peak working memory set: {3} MB", 
                    tasksCount, 
                    elapsedTime, 
                    elapsedTime - dummyTaskDelay,
                    Process.GetCurrentProcess().PeakWorkingSet / 1024 / 1024
                    ) ;   
            }
            
            // Console output
            // 1000 tasks completed in 1033 ms; overhead 33 ms; peak working memory set: 15 MB
            // 10000 tasks completed in 1027 ms; overhead 27 ms; peak working memory set: 23 MB
            // 100000 tasks completed in 1191 ms; overhead 191 ms; peak working memory set: 73 MB
            // 1000000 tasks completed in 4659 ms; overhead 3659 ms; peak working memory set: 431 MB
        }
    }
}