// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Threading; namespace Singleton.Perf { public class Test { private const int NTHREADS = 100; private const int NTASKS = 10000; private const int NREP = 100000; private static void TestRun(string lbl, Action f) { DateTime t1 = DateTime.Now; ThreadPool.SetMinThreads(NTHREADS, NTHREADS); ThreadPool.SetMaxThreads(NTHREADS, NTHREADS); CountdownEvent done = new CountdownEvent(NTASKS); for(int i = 0; i < NTASKS; i++) { ThreadPool.QueueUserWorkItem(o => { for(int j = 0; j < NREP; j++) f(); done.Signal(); } ); } done.Wait(); DateTime t2 = DateTime.Now; Console.WriteLine("{0} : {1} ms", lbl, (long)(t2 - t1).TotalMilliseconds); } public static void Main(string[] args) { for(int i = 0; i < 3; i++) { SimpleSingleton.Instance.Reset(); TestRun("Simple", () => SimpleSingleton.Instance.Increment()); if(SimpleSingleton.Instance.Counter != NTASKS * NREP) { throw new Exception("Oooops"); } SynchronizedSingleton.Instance.Reset(); TestRun("Synchronized", () => SynchronizedSingleton.Instance.Increment()); if(SynchronizedSingleton.Instance.Counter != NTASKS * NREP) { throw new Exception("Oooops"); } VolatileSingleton.Instance.Reset(); TestRun("Volatile", () => VolatileSingleton.Instance.Increment()); if(VolatileSingleton.Instance.Counter != NTASKS * NREP) { throw new Exception("Oooops"); } MemBarrierSingleton.Instance.Reset(); TestRun("MemBarrier", () => MemBarrierSingleton.Instance.Increment()); if(MemBarrierSingleton.Instance.Counter != NTASKS * NREP) { throw new Exception("Oooops"); } HolderSingleton.Instance.Reset(); TestRun("Holder", () => HolderSingleton.Instance.Increment()); if(HolderSingleton.Instance.Counter != NTASKS * NREP) { throw new Exception("Oooops"); } LazySingleton.Instance.Reset(); TestRun("Lazy", () => LazySingleton.Instance.Increment()); if(LazySingleton.Instance.Counter != NTASKS * NREP) { throw new Exception("Oooops"); } } } } }