Example #1
0
        private static void WriteToCacheLoop(ref bool mustLoop, IFixedSizeCache<string, Item> cache, Average average)
        {
            Stopwatch timer = new Stopwatch();
            long counter = 0;
            int startAtCount = cache.MaxItemCount /2;
            while (mustLoop)
            {
                //byte[] charBuffer = new byte[40];
                //_random.NextBytes(charBuffer);
                //string key = Encoding.Unicode.GetString(charBuffer).ToLowerInvariant();

                string key = (Guid.NewGuid().ToString()).PadLeft(Random.Next(40), (char)Random.Next(256));
                //Console.WriteLine(key);
                timer.Restart();
                // ReSharper disable once PossibleNullReferenceException
                cache.GetOrAdd(key, k => EmptyItem);
                timer.Stop();

                if (counter > startAtCount)
                {
                    double averageCallTimeInNs = timer.Elapsed.Ticks*100;
                    average.Add(averageCallTimeInNs);
                }
                counter++;
            }
        }
        private static Stopwatch TimeParralelCacheWrite(IFixedSizeCache<string,int> cache, int loopCount)
        {
            var hammertime = true;

            Task hammerOnCacheTask = Task.Run(() =>
            {

                // ReSharper disable AccessToModifiedClosure
                while (hammertime)

                {
                    for (var i = 0; i < loopCount; i++)
                    {

                        if (hammertime == false)
                        {
                            break;
                        }

                        if (i % 2 == 0)
                        {
                            int i1 = i;
                           cache.GetOrAdd(i1.ToString(), s => i1);
                        }
                        else
                        {
                            int i1 = i;
                            cache.GetOrAdd((i1 - 5).ToString(), s => (i1 - 5));
                        }
                    }
                }
            });
            // ReSharper restore AccessToModifiedClosure

            Stopwatch timer = new Stopwatch();

            timer.Start();
            Parallel.For(0, loopCount, i => { cache.GetOrAdd(i.ToString(), s => i); });

            timer.Stop();
            hammertime = false;
            hammerOnCacheTask.Wait(10);
            return timer;
        }