Skip to content

Sample: Cached write read

Leo Botinelly edited this page Dec 2, 2015 · 1 revision
using System;
using System.Diagnostics;
using System.Linq;
using Faker;
using Nyan.Core.Extensions;
using Nyan.Core.Settings;
using Nyan.Samples.Console.Model;
using System.Collections.Generic;

namespace NyanSample
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            const int amountToTest = 100;

            User.RemoveAll();

            var s = new Stopwatch();

            var IdList = new List<string>();

            s.Restart();

            Current.Log.Add("### Creating " + amountToTest + " records");

            for (var i = 0; i < amountToTest; i++)
            {
                IdList.Add(
                new User
                {
                    Name = Name.First(),
                    Surname = Name.Last(),
                    isAdmin = (RandomNumber.Next(0, 2) == 0),
                    BirthDate = RandomDay()
                }.Save());
            }
            s.Stop();

            Current.Log.Add(s.ElapsedMilliseconds + " ms - {0}/s".format(amountToTest / ((double)s.ElapsedMilliseconds / 1000)));

            Current.Log.Add("### Reading " + IdList.Count + " records, round 1");

            s.Restart();

            foreach (var i in IdList)
            {
                User.Get(i);
            }

            s.Stop();

            double round1Speed = IdList.Count / ((double)s.ElapsedMilliseconds / 1000);

            Current.Log.Add(s.ElapsedMilliseconds + " ms - {0}/s, {1} records fetched".format(IdList.Count / ((double)s.ElapsedMilliseconds / 1000), IdList.Count));

            Current.Log.Add("### Reading " + IdList.Count + " records, round 2");

            s.Restart();

            foreach (var i in IdList)
            {
                User.Get(i);
            }

            s.Stop();

            double round2Speed = IdList.Count / ((double)s.ElapsedMilliseconds / 1000);

            Current.Log.Add(s.ElapsedMilliseconds + " ms - {0}/s, {1} records fetched".format(IdList.Count / ((double)s.ElapsedMilliseconds / 1000), IdList.Count));

            Current.Log.Add("Round 2 was {0} times faster than round 1.".format(round2Speed/ round1Speed));

            Current.Log.Add("Done.");

            System.Console.ReadKey();
        }

        private static DateTime RandomDay()
        {
            var start = new DateTime(1950, 1, 1);
            var gen = new Random();

            var range = (DateTime.Today - start).Days;
            return start.AddDays(gen.Next(range));
        }
    }
}