Example #1
0
        public void Average()
        {
            // arrange
            List<int> listInt = new List<int>() { 1, 2, 3, 4 };
            List<long> listlong = new List<long>() { 1, 2, 3, 4 };
            List<double> listdouble = new List<double>() { 1d, 2d, 3d, 4d };
            List<decimal> listdecimal = new List<decimal>() {
                new decimal(1d),
                new decimal(2d),
                new decimal(3d),
                new decimal(4d)
            };

            // act
            double actualInt = listInt.Average(x => x);
            double actuallong = listlong.Average(x => x);
            double actualdouble = listdouble.Average(x => x);
            decimal actualdecimal = listdecimal.Average(x => x);

            // assert
            Assert.AreEqual(2.5d, actualInt, 0);
            Assert.AreEqual(2.5d, actuallong, 0);
            Assert.AreEqual(2.5d, actualdouble, 0);
            Assert.AreEqual(new decimal(2.5), actualdecimal);
        }
        public void BeginFinalizeTest_SuccessTwoOfThree()
        {
            //Arrange
            decimal success = 0;
            decimal totalFrames = 3;
            
            _dates = new List<DateTime>();
            DateTime now = new DateTime(1,1,1,1,1,0,150);
            for (int i = 0; i < totalFrames+1; i++)
            {
                _dates.Add(now + TimeSpan.FromMilliseconds(300 * i));
            }

            _spans = new List<TimeSpan>() { TimeSpan.FromMilliseconds(15) };

            _timingObj.Now.Returns(_dates[0], _dates[1], _dates[2], _dates[3]);
            _timingObj.Elapsed.Returns(_spans[0]);
            double average = _spans.Average(x => x.Milliseconds);

            //Act
            for (int i = 0; i < totalFrames+1; i++)
            {
                _asset.Begin();
                bool res = i % 2 == 0;
                if (res) success++;
                _asset.Finalize(res);
            }

            //Assert
            Assert.AreEqual(success, _asset.DetectedFPS);
            Assert.AreEqual(totalFrames, _asset.TotalFPS);
            Assert.AreEqual(average, _asset.AverageDetectionTime);
            Assert.AreEqual(Math.Truncate((100*success)/totalFrames), (decimal)_asset.DetectionRate);
        }
        public void Average_Empty_DefaultMoney()
        {
            var source = new List<MoneyStub>();

            var actual = source.Average(s => s.Value);

            Assert.AreEqual(0, actual.Amount);
            Assert.AreEqual("BRL", actual.Currency);
        }
        public void TestAvgProcessingValue()
        {
            int runs = 10000000;
            generator.AvgProcessingTime = 25;
            var runsResult = new List<int>();
            for (int i = 0; i < runs; i++)
            {
                runsResult.Add(generator.AvgProcessingTime);
            }

            var real = runsResult.Average();
            Assert.IsTrue((25 - Math.Floor(real)) < 1);
        }
Example #5
0
 public void MultiAsyncResolvePublicIpTest() {
     var l = new List<long>();
     var n = new FastHttpClient(); //init settings
     Thread.Sleep(3000);
     var sw = new Stopwatch();
     for (int i = 0; i < 20; i++) {
         sw.Restart();
         Assert.IsNotNull(IpResolver.GetPublic());
         Debug.WriteLine(sw.ElapsedMilliseconds);
         l.Add(sw.ElapsedMilliseconds);
     }
     Debug.WriteLine("Average: "+l.Average());
 }
        public void TestAvgIntervalValue()
        {
            int runs = 10000000;
            generator.AvgIntervalTime = 10;
            var runsResult = new List<int>();
            for (int i = 0; i < runs; i++)
            {
                runsResult.Add(generator.NextIntervalTime);
            }

            var real = runsResult.Average();
            Console.WriteLine(Math.Floor(real));
            Assert.IsTrue((10 - Math.Floor(real)) < 1);
        }
        public void Average_Source_Money()
        {
            var source = new List<MoneyStub>()
            {
                new MoneyStub() { Value = Money.Reais(1) },
                new MoneyStub() { Value = Money.Reais(2) },
                new MoneyStub() { Value = Money.Reais(3) }
            };

            var actual = source.Average(s => s.Value);

            Assert.AreEqual(2, actual.Amount);
            Assert.AreEqual("BRL", actual.Currency);
        }
Example #8
0
        public void TestNextDouble()
        {
            var random = new NormalRandom();
            var list = new List<double>();
            for (int i = 0; i < 10000000; i++)
            {
                var value = random.NextDouble();
                //Console.WriteLine(value);
                list.Add(value);
            }

            Console.WriteLine();
            Console.WriteLine("平均: {0}", list.Average());
            Console.WriteLine("分散: {0}", VarP(list.ToArray()));
        }
Example #9
0
        public void ShorcikLinqTest()
        {
            List<ListLinq> lista = new List<ListLinq>();
            lista.Add(new ListLinq() {Imie = "Rafal", Nazwisko = "Bedkowski", Wiek = 40});
            lista.Add(new ListLinq() {Imie = "Mariusz", Nazwisko = "Mularczyk", Wiek = 16});
            lista.Add(new ListLinq() {Imie = "Bartłomiej", Nazwisko = "Korcz", Wiek = 25});
            lista.Add(new ListLinq() {Imie = "Adam", Nazwisko = "Ficek", Wiek = 33});
            lista.Add(new ListLinq() {Imie = "Amelia", Nazwisko = "Dydko", Wiek = 46});

            var counter = lista.Count;
            var wynik = lista.Where(x=>x.Imie.Equals("Rafal"));
            var latka = lista.Where(x => x.Wiek > 25);
            var next = lista.Average(x => x.Wiek);
            Console.ReadKey();
        }
        public void ByProjectShouldReturnFastResponse()
        {
            var allResponseTimes = new List<double>();

            for (int i = 0; i < 10; i++)
            {
                MyWebApi
                    .Server()
                    .Working()
                    .WithHttpRequestMessage(req => req
                        .WithRequestUri("api/Commits/ByProject/1")
                        .WithMethod(HttpMethod.Get))
                    .ShouldReturnHttpResponseMessage()
                    .WithResponseTime(time =>
                    {
                        allResponseTimes.Add(time.TotalMilliseconds);
                    });
            }

            Assert.IsTrue(allResponseTimes.Average() < 100);
        }
        public void AverageTest()
        {
            List<int> posIntList = new List<int>();
            List<int> intList = new List<int>();
            List<decimal> posDecimalList = new List<decimal>();
            List<decimal> decimalList = new List<decimal>();
            int sign = -1;

            for (int i = 0; i < 10; i++)
            {
                posIntList.Add(i + 1);
                intList.Add((i + 1) * sign);
                posDecimalList.Add((i + 1) / 10m);
                decimalList.Add(((i + 1) / 10m) * sign);
                sign *= -1;
            }

            Assert.AreEqual(5, posIntList.Average());
            Assert.AreEqual(0, intList.Average());
            Assert.AreEqual(.55m, posDecimalList.Average());
            Assert.AreEqual(.05m, decimalList.Average());
        }
Example #12
0
        public void TimedTest_PassingInQueryText()
        {
            var times = new List<long>();
            var profiler = new Stopwatch();

            using (var db = CreateAccessDB())
            {
                db.SqlMode = SqlModes.Text;

                for (int i = 1; i <= 4; i++)
                {
                    profiler.Restart();

                    string sql = @"SELECT Product.ID, Product.Name, Product.Description, Product.Price, Product.CategoryID, Product.ImageFileName, Product.NewItem, Product.IsSplash, Category.Name AS CategoryName, Option.OptionTypeID, OptionType.Type, OptionType.MultiPick, Option.ID AS OptionID, Option.Description AS OptionDescription, Option.Price AS OptionPrice
                                   FROM ((Category LEFT JOIN OptionType ON Category.ID = OptionType.CategoryID) RIGHT JOIN Product ON Category.ID = Product.CategoryID) LEFT JOIN [Option] ON OptionType.ID = Option.OptionTypeID;";
                    var products = db.Query<Product>().QueryText(sql).Graph().ToList();

                    profiler.Stop();

                    if (products.Count == 0)
                        throw new Exception("Result set was empty");

                    Trace.WriteLine(string.Format("iteration {0} : {1}ms", i, profiler.ElapsedMilliseconds));
                    times.Add(profiler.ElapsedMilliseconds);
                }
            }

            Trace.WriteLine("---------------");
            times.RemoveAt(0);
            Trace.WriteLine(string.Format("Average time after inital load: {0}", times.Average()));
        }
Example #13
0
        public void TestLinqAverage2()
        {
            var connectionString = _connectionString + "StoreName=" + Guid.NewGuid();
            var context = new MyEntityContext(connectionString);
            var ages = new List<int>();
            for (int i = 0; i < 1000; i++)
            {
                var entity = context.Entities.Create();
                entity.SomeString = "Person" + i;
                int age = 20 + (i / 20);
                entity.SomeInt = age;
                ages.Add(age);
            }
            context.SaveChanges();

            var total1 = context.Entities.Sum(e => e.SomeInt);
            var total2 = ages.Sum();

            var q1 = context.Entities.Count();
            var q2 = ages.Count;

            Assert.AreEqual(total2 / q2, total1 / q1);

            Assert.AreEqual(1000, context.Entities.Count());

            Assert.AreEqual(ages.Average(), context.Entities.Average(e => e.SomeInt));
        }
Example #14
0
        public static void Benchmark(Action codeToTest, double previousResult = 0)
        {
            // Up the thread priority.
            var priorPriority = System.Threading.Thread.CurrentThread.Priority;
            System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;
            try
            {
                // Get the test name from a stack trace.
                var testName = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name;

                // Measure the test overhead.
                Action emptyAction = () => { };
                var stopWatch = System.Diagnostics.Stopwatch.StartNew();
                for (int i = 0; i < 100; i++)
                    emptyAction();
                long overheadInTicks = stopWatch.ElapsedTicks / 100;

                // Make sure the code is jitted.
                codeToTest();

                // Run the test a number of times.
                long totalTimeRemaining = System.Diagnostics.Stopwatch.Frequency * 2;
                var elapsedTimes = new List<long>();
                while (totalTimeRemaining > 0)
                {
                    // Reset the stopwatch.
                    stopWatch.Restart();

                    // Run the code to test.
                    codeToTest();

                    // Record the time taken.
                    long elapsed = Math.Max(stopWatch.ElapsedTicks - overheadInTicks, 0);
                    elapsedTimes.Add(elapsed);

                    // Collect all garbage.
                    System.GC.Collect();

                    // Check if we have run for the required amount of time.
                    totalTimeRemaining -= stopWatch.ElapsedTicks;
                }

                double average = elapsedTimes.Average();
                //double variance = elapsedTimes.Select(e => Math.Pow(average - e, 2)).Average();
                //double deviation = Math.Sqrt(variance);
                double min = Math.Sqrt(elapsedTimes.Where(e => e <= average).Select(e => Math.Pow(average - e, 2)).Average());
                double max = Math.Sqrt(elapsedTimes.Where(e => e >= average).Select(e => Math.Pow(average - e, 2)).Average());

                // Convert to milliseconds.
                double ticksToMilliseconds = 1000.0 / (double)System.Diagnostics.Stopwatch.Frequency;
                average *= ticksToMilliseconds;
                //variance *= ticksToMilliseconds;
                //deviation *= ticksToMilliseconds;
                min *= ticksToMilliseconds;
                max *= ticksToMilliseconds;

                // Output the time taken.
                //Console.WriteLine("Performance test '{0}' took {1:f1} ± {2:f1} milliseconds.", testName, average, deviation * 2);
                for (int i = 0; i < elapsedTimes.Count; i++)
                    Console.WriteLine("Test #{0}: {1:g3} milliseconds.", i + 1, elapsedTimes[i] * ticksToMilliseconds);

                // Show the results in the unit test error message column.
                throw new AssertInconclusiveException(string.Format("{0:g3} operations/sec (± {1:g2}), was {2}",
                    1000.0 / average, (1000.0 / (average - min) - 1000.0 / (average + max)) / 2, previousResult));

                //if (testName != null)
                //{
                //    string outputDir = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(typeof(AssertUtils).Assembly.Location), @"..\..\..\Performance Tests\");
                //    if (System.IO.Directory.Exists(outputDir) == false)
                //        System.IO.Directory.CreateDirectory(outputDir);
                //    string outputPath = System.IO.Path.Combine(outputDir, testName + ".csv");
                //    if (System.IO.File.Exists(outputPath) == false)
                //        System.IO.File.WriteAllText(outputPath, "Time,Sample,Variance");
                //    System.IO.File.AppendAllText(outputPath, string.Format("\r\n{0:yyyy'-'MM'-'dd HH':'mm':'ss},{1:f1},{2:f1}", DateTime.Now, average, deviation));
                //}
            }
            finally
            {
                // Revert the thread priority.
                System.Threading.Thread.CurrentThread.Priority = priorPriority;
            }
        }
Example #15
0
        static void CrudTest(ISimpleEmployeeRepository repo)
        {
            s_DataSource.Sql(@"DELETE FROM Sales.Customer;DELETE FROM HR.Employee;").Execute();

            //actual
            var spans = new List<double>(Iterations);
            for (var i = 0; i < Iterations; i++)
            {
                var sw = Stopwatch.StartNew();
                CrudTestCore(repo);
                sw.Stop();
                spans.Add(sw.Elapsed.TotalMilliseconds);
            }
            Trace.WriteLine("Run Duration: " + spans.Average().ToString("N2") + " ms per iteration. Min: " + spans.Min().ToString("N2") + " ms. Max: " + spans.Max().ToString("N2") + " ms.");

            Trace.WriteLine("");
            Trace.WriteLine("");
            //foreach (var span in spans)
            //    Trace.WriteLine("    " + span.ToString("N2"));

            if (DiscardHighLow && Iterations > 10)
            {
                //Remove the highest and lowest two to reduce OS effects
                spans.Remove(spans.Max());
                spans.Remove(spans.Max());
                spans.Remove(spans.Min());
                spans.Remove(spans.Min());
            }

            Trace.WriteLine("Run Duration: " + spans.Average().ToString("N2") + " ms per iteration. Min: " + spans.Min().ToString("N2") + " ms. Max: " + spans.Max().ToString("N2") + " ms.");

            long frequency = Stopwatch.Frequency;
            Trace.WriteLine($"  Timer frequency in ticks per second = {frequency}");
            long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;
            Trace.WriteLine($"  Timer is accurate within {nanosecPerTick} nanoseconds");
        }
Example #16
0
        protected void TestExtremelyLong()
        {
            const int SLEEP_TIME_MS = 10;
            int THREADS = System.Environment.ProcessorCount;
            const float TARGET_CPU_LOAD = 0.4f;

            Assert.IsTrue(THREADS <= System.Environment.ProcessorCount);

            ProgressIndicator pi = new ProgressIndicator("Crypto +4GB Test");

            pi.AddLine(String.Format("Configuration: {0} threads, CPU Load: {1}%", THREADS, TARGET_CPU_LOAD * 100));

            CancellationTokenSource src = new CancellationTokenSource();

            Task regulator = Task.Factory.StartNew(token =>
            {
                PerformanceCounter pc = new PerformanceCounter("Processor", "% Processor Time", "_Total");

                List<float> cpu_load = new List<float>();

                for (;;)
                {
                    const int PROBE_DELTA_MS = 200;
                    const int PROBE_COUNT = 30;
                    const int REGULATE_COUNT = 10;

                    for (int i = 0; i < REGULATE_COUNT; i++)
                    {
                        System.Threading.Thread.Sleep(PROBE_DELTA_MS);

                        cpu_load.Add(pc.NextValue() / 100);

                        if (src.IsCancellationRequested)
                            break;
                    }

                    while (cpu_load.Count > PROBE_COUNT)
                        cpu_load.RemoveFirst();

                    int old_transform_rounds = transform_rounds;

                    float avg_cpu_load = cpu_load.Average();

                    if (avg_cpu_load >= TARGET_CPU_LOAD)
                    {
                        transform_rounds = (int)Math.Round(transform_rounds * 0.9);

                        if (old_transform_rounds == transform_rounds)
                            transform_rounds--;
                    }
                    else
                    {
                        transform_rounds = (int)Math.Round(transform_rounds * 1.1);

                        if (old_transform_rounds == transform_rounds)
                            transform_rounds++;
                    }

                    if (transform_rounds == 0)
                        transform_rounds = 1;

                    if (src.IsCancellationRequested)
                        break;
                }
            }, src.Token);

            var partitioner = Partitioner.Create(Hashes.CryptoAll, EnumerablePartitionerOptions.None);

            Parallel.ForEach(partitioner, new ParallelOptions() { MaxDegreeOfParallelism = THREADS }, ht =>
            {
                IHash hash = (IHash)Activator.CreateInstance(ht);

                pi.AddLine(String.Format("{0} / {1} - {2} - {3}%", Hashes.CryptoAll.IndexOf(ht) + 1,
                    Hashes.CryptoAll.Count, hash.Name, 0));

                TestData test_data = TestData.Load(hash);

                int test_data_index = 0;

                for (int i = 0; i < test_data.Count; i++)
                {
                    if (test_data.GetRepeat(i) == 1)
                        continue;

                    test_data_index++;

                    ulong repeats = (ulong)test_data.GetRepeat(i);
                    byte[] data = test_data.GetData(i);
                    string expected_result = Converters.ConvertBytesToHexString(test_data.GetHash(i));

                    hash.Initialize();

                    int transform_counter = transform_rounds;
                    DateTime progress = DateTime.Now;

                    for (ulong j = 0; j < repeats; j++)
                    {
                        hash.TransformBytes(data);

                        transform_counter--;
                        if (transform_counter == 0)
                        {
                            System.Threading.Thread.Sleep(SLEEP_TIME_MS);
                            transform_counter = transform_rounds;
                        }

                        if (DateTime.Now - progress > TimeSpan.FromSeconds(5))
                        {
                            pi.AddLine(String.Format("{0} / {1} / {2} - {3} - {4}%", Hashes.CryptoAll.IndexOf(ht) + 1,
                                test_data_index, Hashes.CryptoAll.Count, hash.Name, j * 100 / repeats));
                            progress = DateTime.Now;
                        }
                    }

                    HashResult result = hash.TransformFinal();

                    Assert.AreEqual(expected_result, Converters.ConvertBytesToHexString(result.GetBytes()), hash.ToString());

                    pi.AddLine(String.Format("{0} / {1} / {2} - {3} - {4}", Hashes.CryptoAll.IndexOf(ht) + 1,
                        test_data_index, Hashes.CryptoAll.Count, hash.Name, "OK"));
                }
            });

            src.Cancel();
            regulator.Wait();
        }
Example #17
0
        public void Average_abnormal()
        {
            // arrange
            List<int> listInt = new List<int>() { 1, 2, 3, 4 };
            List<long> listLong = new List<long>() { 1, 2, 3, 4 };
            List<double> listDouble = new List<double>() { 1d, 2d, 3d, 4d };
            List<decimal> listBigDecimal = new List<decimal>() {
                new decimal(1d),
                new decimal(2d),
                new decimal(3d),
                new decimal(4d)
            };

            List<int> listIntEmpty = new List<int>();
            List<long> listLongEmpty = new List<long>();
            List<double> listDoubleEmpty = new List<double>();
            List<decimal> listBigDecimalEmpty = new List<decimal>();

            Func<int, int> funcInt = null;
            Func<long, int> funcLong = null;
            Func<double, int> funcDouble = null;
            Func<decimal, int> funcDecimal = null;

            // act and assert
            try
            {
                listInt.Average(funcInt);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is ArgumentNullException);
            }
            try
            {
                listIntEmpty.Average(x => x);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is InvalidOperationException);
            }

            try
            {
                listLong.Average(funcLong);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is ArgumentNullException);
            }
            try
            {
                listLongEmpty.Average(x => x);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is InvalidOperationException);
            }

            try
            {
                listDouble.Average(funcDouble);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is ArgumentNullException);
            }
            try
            {
                listDoubleEmpty.Average(x => x);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is InvalidOperationException);
            }

            try
            {
                listBigDecimal.Average(funcDecimal);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is ArgumentNullException);
            }
            try
            {
                listBigDecimalEmpty.Average(x => x);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is InvalidOperationException);
            }
        }
Example #18
0
        public void Average_overflow()
        {
            // arrange
            List<int> listOverflowInt = new List<int>() { int.MaxValue, 1 };
            List<int> listUnderflowInt = new List<int>() { int.MinValue, -1 };
            List<long> listOverflowLong = new List<long>() { long.MaxValue, 1 };
            List<long> listUnderflowLong = new List<long>() { long.MinValue, -1 };

            // act and assert
            try
            {
                listOverflowInt.Average(x => x);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is OverflowException);
            }
            try
            {
                listUnderflowInt.Average(x => x);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is OverflowException);
            }

            try
            {
                listOverflowLong.Average(x => x);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is OverflowException);
            }
            try
            {
                listUnderflowLong.Average(x => x);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is OverflowException);
            }
        }
Example #19
0
        public void Given_SpawnHive_valid_Should_NOT_Hit_random_bee()
        {
            //  Arrange
            var random = new Random((int)DateTime.Now.Ticks & 0x0000FFFF);
            var sut = new BeeGame().Start(settings);
            var container = new List<int>();
            var hive = new Hive();

            //  Act
            for (int i = 0; i < 25; i++)
            {
                var bee = sut.Hive[1];
                container.Add(sut.Hive.IndexOf(bee));
            }
            var result = container.Average();

            //  Assert
            Assert.AreEqual(container[0], result);
        }
        public void BeginFinalizeTest_SuccessAllOfFive()
        {
            //Arrange
            decimal success = 5;
            decimal totalFrames = 5;

            _dates = new List<DateTime>();
            DateTime now = new DateTime(1, 1, 1, 1, 1, 0, 550);
            for (int i = 0; i < totalFrames + 1; i++)
            {
                _dates.Add(now + TimeSpan.FromMilliseconds(100 * i));
            }

            _spans = new List<TimeSpan>() { TimeSpan.FromMilliseconds(25),
                                            TimeSpan.FromMilliseconds(10),
                                            TimeSpan.FromMilliseconds(9),
                                            TimeSpan.FromMilliseconds(5),
                                            TimeSpan.FromMilliseconds(30) };

            _timingObj.Now.Returns(_dates[0], _dates[1], _dates[2], _dates[3], _dates[4], _dates[5] );
            _timingObj.Elapsed.Returns(_spans[0], _spans[1], _spans[2], _spans[3], _spans[4]);
            double average = _spans.Average(x => x.Milliseconds);

            //Act
            for (int i = 0; i < totalFrames + 1; i++)
            {
                _asset.Begin();
                _asset.Finalize(true);
            }

            //Assert
            Assert.AreEqual(success, _asset.DetectedFPS);
            Assert.AreEqual(totalFrames, _asset.TotalFPS);
            Assert.AreEqual(Math.Truncate(average), _asset.AverageDetectionTime);
            Assert.AreEqual(100, (decimal)_asset.DetectionRate);
        }
Example #21
0
        public void TimedTest_AccessQuery()
        {
            var times = new List<long>();
            var profiler = new Stopwatch();

            using (var db = CreateAccessDB())
            {
                for (int i = 1; i <= 4; i++)
                {
                    profiler.Restart();

                    var products = db.Query<Product>().FromView("V_Product").Graph().ToList();

                    profiler.Stop();

                    if (products.Count == 0)
                        throw new Exception("Result set was empty");

                    Trace.WriteLine(string.Format("iteration {0} : {1}ms", i, profiler.ElapsedMilliseconds));
                    times.Add(profiler.ElapsedMilliseconds);
                }
            }

            Trace.WriteLine("---------------");
            times.RemoveAt(0);
            Trace.WriteLine(string.Format("Average time after inital load: {0}", times.Average()));
        }
        public async Task PerfomanceParallelCreateTest()
        {
            System.Diagnostics.Debug.Print("Start " + DateTime.Now.ToShortTimeString());

            Stopwatch stopwatch = new Stopwatch();
            var watch = new List<TimeSpan>();

            Parallel.For(0, 1000, (i) =>
            {
                stopwatch.Start();

                PostTest();

                stopwatch.Stop();
                watch.Add(stopwatch.Elapsed);
                stopwatch.Reset();
            });


            var count = watch.Count();
            var avg = watch.Average(r => r.Milliseconds);
            var min = watch.Min(r => r.Milliseconds);
            var max = watch.Max(r => r.Milliseconds);

            System.Diagnostics.Debug.Print("avg: {0}, min: {1}, max: {2}, count: {3}", avg, min, max, count);
            System.Diagnostics.Debug.Print("End " + DateTime.Now.ToShortTimeString());
        }
        public async Task PerfomanceCreateTest()
        {
            System.Diagnostics.Debug.Print("Start " + DateTime.Now.ToShortTimeString());

            Stopwatch stopwatch = new Stopwatch();
            var watch = new List<TimeSpan>();

            System.Linq.Enumerable.Range(0, 1000).ToList().ForEach(r => {
                stopwatch.Start();
                PostTest();

                stopwatch.Stop();
                watch.Add(stopwatch.Elapsed);
                stopwatch.Reset();
            });

            var avg = watch.Average(r => r.Milliseconds);
            var min = watch.Min(r => r.Milliseconds);
            var max = watch.Max(r => r.Milliseconds);

            System.Diagnostics.Debug.Print("avg: {0}, min: {1}, max: {2} ", avg, min, max);
            System.Diagnostics.Debug.Print("End " + DateTime.Now.ToShortTimeString());
        }
        public void Perf_MeasureScenario1()
        {
            // The test can be run against LTS simply by changing the service
            // type to TestDomainServices.LTS.Northwind
            Type serviceType = typeof(TestDomainServices.EF.Northwind);

            DateTime before, after;
            TimeSpan diff;
            List<double> times = new List<double>();
            Dictionary<string, object> queryParameters = new Dictionary<string, object> { {"$take", 500} };

            for (int i = 0; i < 10; i++)
            {
                before = DateTime.Now;
                string soap = RequestDirect(serviceType, "GetOrders", queryParameters);
                after = DateTime.Now;

                Assert.IsTrue(soap.Contains("<ResultCount>500</ResultCount>"));

                diff = after - before;
                times.Add(diff.TotalSeconds);
            }

            double avgTime = times.Average();
            Console.WriteLine("Average time for Perf_MeasureScenario1 : {0} seconds", avgTime);
        }
Example #25
0
 public void TestPeriodicTaskCall5Times()
 {
     DateTime prevRun = DateTime.UtcNow;
     List<TimeSpan> intervals = new List<TimeSpan>();
     int calls = 0;
     var scheduler = CreateScheduler();
     scheduler.AddTask(
         new ScheduledTask
         {
             TaskAction = () =>
             {
                 calls++;
                 TimeSpan interval = DateTime.UtcNow - prevRun;
                 prevRun = DateTime.UtcNow;
                 intervals.Add(interval);
             },
             IntervalType = IntervalTypes.Periodic,
             Interval = TimeSpan.FromMilliseconds(100)
         });
     Thread.Sleep(600);
     double averageInterval = intervals.Average(s => s.TotalMilliseconds);
     if (Math.Abs(100 - averageInterval) > 10) Assert.Fail("Average interval is " + averageInterval);
 }