Skip to content

Task Based IdGenerator Performance Test

piranout edited this page Jun 30, 2015 · 1 revision

This program will both performance test and stress test the Id generator. Add the IdGenerators NuGet package to a new console project. Then replace the contents of Program.cs with the following.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading.Tasks;
using Funcular.IdGenerators.Base36;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main()
        {
            // Create 25 character long Ids. When generated with param
            // delimiter: true, they will appear as 5 groups of 5 charcters:
            var generator = new Base36IdGenerator(
                numTimestampCharacters: 12, 
                numServerCharacters: 6, 
                numRandomCharacters: 7, 
                reservedValue: "", 
                delimiter: "-", 
                delimiterPositions: new[] {20, 15, 10, 5});
            // Check each Id for duplication:
            var dict = new ConcurrentDictionary<string, string>();
            var tasks = new Task[10];
            // Performance testing; some benchmarks: An old 2.27Ghz Core2 Duo
            // generated a little over 54,000 Ids per second. A 3Ghz Core i7 
            // generated about 220,000 Ids per second.
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < tasks.Length; i++)
            {
                tasks[i] = Task.Factory.StartNew(() =>
                {
                    while (sw.ElapsedMilliseconds < 10000)
                    {
                        if (!dict.TryAdd(generator.NewId(), ""))
                        {
                            // You should never see an Id collision. If you 
                            // can create a reproducible example that generates
                            // duplicate Ids, please file a bug report.
                            throw new Exception("Duplicate Id, fail!");
                        }
                    }
                });
            }
            Task.WaitAll(tasks);
            sw.Stop();
            Console.WriteLine("Done! {0} ids generated in {1}", dict.Count, sw.Elapsed);
        }
    }
}