コード例 #1
0
        public void Compare()
        {
            Random random = new Random();

            Stopwatch totalStopwatch = new Stopwatch();

            totalStopwatch.Start();

            Stopwatch sw1 = new Stopwatch();
            Stopwatch sw2 = new Stopwatch();
            Stopwatch sw3 = new Stopwatch();
            Stopwatch sw4 = new Stopwatch();

            var flags = new int[] { 0, 1, 2, 3 };

            for (int i = 0; i < 1024 * 256 * 32; i++)
            {
                byte[] x;
                byte[] y;

                if (random.Next(0, 2) == 0)
                {
                    var length = random.Next(0, 1024);
                    x = new byte[length];
                    y = new byte[length];
                }
                else
                {
                    x = new byte[random.Next(0, 1024)];
                    y = new byte[random.Next(0, 1024)];
                }

                if (random.Next(0, 2) == 0)
                {
                    random.NextBytes(x);
                    random.NextBytes(y);
                }

                int result1 = 0;
                int result2 = 0;
                int result3 = 0;
                int result4 = 0;

                var maxLength = Math.Min(x.Length, y.Length);

                random.Shuffle(flags);
                foreach (var index in flags)
                {
                    if (index == 0)
                    {
                        sw1.Start();
                        result1 = Unsafe.Compare(x, y);
                        sw1.Stop();
                    }
                    else if (index == 1)
                    {
                        sw2.Start();
                        result2 = Unsafe.Compare2(x, y);
                        sw2.Stop();
                    }
                    else if (index == 2)
                    {
                        sw3.Start();
                        result3 = Unsafe.Compare(x, 0, y, 0, maxLength);
                        sw3.Stop();
                    }
                    else if (index == 3)
                    {
                        sw4.Start();
                        result4 = Unsafe.Compare2(x, 0, y, 0, maxLength);
                        sw4.Stop();
                    }
                }

                Assert.IsTrue(result1 == result2);
                Assert.IsTrue(result3 == result4);

                if (totalStopwatch.ElapsedMilliseconds > 1000 * 60)
                {
                    break;
                }
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("Native Compare: " + sw1.Elapsed.ToString());
            sb.AppendLine("Native Compare2: " + sw2.Elapsed.ToString());
            sb.AppendLine("Native Compare: " + sw3.Elapsed.ToString());
            sb.AppendLine("Native Compare2: " + sw4.Elapsed.ToString());

            Console.WriteLine(sb.ToString());
        }