예제 #1
0
 static void Main(string[] args)
 {
     PerformanceTest performanceTest = new PerformanceTest();
     //performanceTest.GroupJoin();
     //performanceTest.MySkipListVsLomontLookups();
     //performanceTest.MySkipListVsLomontAdds();
     //performanceTest.SkipListVsSortedDictionaryAdds();
     //performanceTest.SkipListVsSortedDictionaryLookups();
     //performanceTest.LlrbtVsSortedDictionaryAdds();
     //performanceTest.LlrbtVsSortedDictionaryLookups();
     //performanceTest.RecursiveFunctionVsStack();
     //performanceTest.CompareQueryCreation();
     //performanceTest.GetInterfaceTest();
     //performanceTest.MemoryTest();
     //performanceTest.SortingTest();
     //performanceTest.TestDynamicProperty();
     //performanceTest.TestDynamicInvoke();
     //performanceTest.SelectTest();
     //performanceTest.SelectLinearUpdateTest();
     //performanceTest.SelectUnrelatedPropertyLinearUpdateTest();
     //performanceTest.WhereTest();
     //performanceTest.ContinuousSumWithoutPausing();
     //performanceTest.ContinuousSumWithPausing();
     //performanceTest.TakeTest();
     //performanceTest.SkipTest();
     performanceTest.SkipTakeCombineAssertTest();
 }
        private static void RunEFMapping100Tests()
        {
            var count = 100;

            PerformanceTest.Run("EF Mapping Test 100 objects",
                                () =>
            {
                using (var db = new BlogContext())
                {
                    var users = db.Users.Take(count).Select(x => new AnotherUserDto
                    {
                        UserId             = x.Id,
                        FullName           = string.Concat(x.FirstName, " ", x.SurName, " ", x.LastName),
                        About              = x.About,
                        CreatedUtcDateTime = x.CreatedUtcDateTime,
                        DeleteUtcDateTime  = x.DeleteUtcDateTime,
                        IsPartner          = x.IsPartner,
                        IsWithoutAccess    = x.IsWithoutAccess,
                        Login              = x.Login,
                        Password           = x.Password,
                        Rating             = x.Rating
                    }).ToList();

                    var user = users.OrderBy(x => x.FullName).First();

                    return(PtopResultName);
                }
            },
                                () =>
            {
                using (var db = new BlogContext())
                {
                    var users = db.Users.Take(count).ProjectToList <AnotherUserDto>();

                    var user = users.OrderBy(x => x.FullName).First();

                    return(MapperResultName);
                }
            });
        }
        private static void RunSampleMapping10KTest()
        {
            var blogs = Config.CreateObjects <BlogPost>(10000);

            PerformanceTest.Run("Sample Mapping Test 10K objects",
                                () =>
            {
                var dtos = new List <BlogPostDto>();

                foreach (var blog in blogs)
                {
                    dtos.Add(new BlogPostDto
                    {
                        Id                    = blog.Id,
                        Content               = blog.Content,
                        Description           = blog.Description,
                        LastUpdateUtcDateTime = blog.LastUpdateUtcDateTime,
                        DeleteUtcDateTime     = blog.DeleteUtcDateTime,
                        LinkedPosts           = blog.LinkedPosts,
                        PublishedUtcDateTime  = blog.PublishedUtcDateTime,
                        RawContent            = blog.RawContent,
                        SocialDescription     = blog.SocialDescription,
                        Title                 = blog.Title
                    });
                }

                var blogDto = dtos.LastOrDefault();

                return(PtopResultName);
            },
                                () =>
            {
                var dtos = _mapper.Map <List <BlogPostDto> >(blogs);

                var blogDto = dtos.LastOrDefault();

                return(MapperResultName);
            });
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            PerformanceTest p = new PerformanceTest();

            p.SetCount(1);             //循环次数(默认:1)
            p.SetIsMultithread(false); //是否启动多线程测试 (默认:false)
            p.Execute(
                i =>
            {
                Object[] args = new Object[] { 0 };
                var assembly  = CreateReflection.NewAssembly();
                var type      = ReflectionUtil.GetType(assembly, "Test.Class1");
                Object obj    = type.InvokeMember(null,
                                                  BindingFlags.DeclaredOnly |
                                                  BindingFlags.Public | BindingFlags.NonPublic |
                                                  BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
                Console.WriteLine("Type: " + obj.GetType().ToString());
                Console.WriteLine("The value of x after the constructor returns is {0}.", args[0]);
                DataTable dt = new DataTable();
                DataRow dr1  = dt.NewRow();
                dt.Columns.Add("key");
                dt.Columns.Add("value");
                dr1["key"]   = "1";
                dr1["value"] = "2";
                dt.Rows.Add(dr1);

                type.InvokeMember("GetList",
                                  BindingFlags.DeclaredOnly |
                                  BindingFlags.Public | BindingFlags.NonPublic |
                                  BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { dt });
            },
                message =>
            {
                //输出总共运行时间
                Response.Write(message);   //总共执行时间:1.02206秒
            }
                );
        }
    public static void Main()
    {
        #if false
        // Functional test
        {
            FuncTest_ReaderWriterGate ftrwg = new FuncTest_ReaderWriterGate();
            ReaderWriterGate gate = new ReaderWriterGate(false);
            ftrwg.SimpleTest(gate);
            ftrwg.TestAll(gate);
        }
        #endif
        // Return value test
        {
            ReaderWriterGate gate = new ReaderWriterGate(false);
            gate.BeginRead(releaser => {
                releaser.ResultValue = "Releasing";
                releaser.Release(false);
                Thread.Sleep(5000);
                Object o = null;
                o.GetType();
                return "Returning";

            }, ar => Console.WriteLine(gate.EndRead(ar)));
            Console.ReadLine();
        }
        // Performance test
        {
            const Int32 c_PerfIterations = 10 * 1000 * 1000;

            ReaderWriterGate gate = new ReaderWriterGate();
            PerformanceTest pt = new PerformanceTest(c_PerfIterations);
            foreach (Boolean write in new Boolean[] { false, true }) {
                Console.WriteLine("{0} {1} {2}",
                   pt.Test(write, gate), write ? "writing" : "reading", gate.ToString());
            }
        }
    }
예제 #6
0
    public static List <PerformanceTest> getTestsFromClassByReflection(object obj)
    {
        List <PerformanceTest> result = new List <PerformanceTest>();

        foreach (MethodInfo methodInfo in obj.GetType().GetMethods())
        {
            string prefix = "test_";
            if (methodInfo.Name.StartsWith(prefix))
            {
                PerformanceTest test = new PerformanceTest();
                test.name            = methodInfo.Name.Substring(prefix.Length);
                test.runAndGetRounds = () => {
                    object testResult = methodInfo.Invoke(obj, new object[0]);
                    if (testResult == null)
                    {
                        throw new Exception("Test should return number of rounds");
                    }
                    return((long)testResult);
                };
                result.Add(test);
            }
        }
        return(result);
    }
예제 #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            PerformanceTest pt = new PerformanceTest();

            pt.SetCount(100000);//设置循环次数
            Models.Student ss = new Models.Student()
            {
                id = 1
            };
            pt.Execute(i =>
            {
                ResolveExpress r = new ResolveExpress();
                Expression <Func <Models.InsertTest, bool> > func = x => x.id > ss.id;
                r.ResolveExpression(r, func);
            }, m => { }, "lambda");


            //输出测试页面
            GridView gv = new GridView();

            gv.DataSource = pt.GetChartSource();
            gv.DataBind();
            Form.Controls.Add(gv);
        }
        public void ResizeTest(int sw, int sh, int tw, int th)
        {
            Size sourceSize = new Size(sw, sh);
            Size targetSize = new Size(tw, th);

            using var bmpRef = Icons.Information.ExtractBitmap(sourceSize);

            var perfTest = new PerformanceTest {
                Iterations = 100, CpuAffinity = null, TestName = $"{sw}x{sh} to {tw}x{th}"
            };

            foreach (var mode in new[] { InterpolationMode.NearestNeighbor, InterpolationMode.Bilinear, InterpolationMode.HighQualityBicubic })
            {
                perfTest.AddCase(() =>
                {
                    using Bitmap result = new Bitmap(sw, sh);
                    using (Graphics g = Graphics.FromImage(result))
                    {
                        g.InterpolationMode = mode;
                        g.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                        g.DrawImage(bmpRef, new Rectangle(Point.Empty, targetSize), new Rectangle(Point.Empty, sourceSize), GraphicsUnit.Pixel);
                        g.Flush();
                    }
                }, $"DrawImage/{mode}");
            }

            foreach (ScalingMode scalingMode in Enum <ScalingMode> .GetValues())
            {
                perfTest.AddCase(() =>
                {
                    using var result = bmpRef.Resize(targetSize, scalingMode);
                }, $"Resize/{scalingMode}");
            }

            perfTest.DoTest().DumpResults(Console.Out);
        }
예제 #9
0
파일: Program.cs 프로젝트: fthoms/jiminy
        static void Main(string[] args)
        {
            var test = new PerformanceTest();

            test.Run();
        }
        public void CompareProfilingWaysCheapOperation()
        {
            const int iterations = 10000000;

            // 1. Test without warm up
            var test = new PerformanceTest <int>
            {
                TestName   = "DoTest performance without warm up",
                Iterations = iterations,
                WarmUp     = false,
                Repeat     = 5,
            }
            .AddCase(DoNothing, nameof(DoNothing));

            test.DoTest().DumpResults(Console.Out);

            // 2. Test without warm up
            test.TestName = "DoTest performance with warm up";
            test.WarmUp   = true;
            test.DoTest().DumpResults(Console.Out);

            // 3. Direct test
            Console.WriteLine("===========Direct measurement test===============");
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            // warming up
            for (int i = 0; i < iterations; i++)
            {
                DoNothing();
            }

            Stopwatch watch = new Stopwatch();

            watch.Start();
            for (int i = 0; i < iterations; i++)
            {
                DoNothing();
            }

            watch.Stop();
            Console.WriteLine("Total Time: {0:N2} ms", watch.Elapsed.TotalMilliseconds);
            Console.WriteLine();
            Console.WriteLine("The difference of DoTest and Direct measurement is the overhead cost of using a delegate in DoTest.");
            Console.WriteLine();

            // 4. Profiler test
            Console.WriteLine("===========Profiler test===============");
            Profiler.Reset();
            Profiler.AutoSaveResults = false;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            for (int i = 0; i < iterations; i++)
            {
                using (Profiler.Measure("ProfilerTest", "WarmingUp"))
                {
                }
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            for (int i = 0; i < iterations; i++)
            {
                using (Profiler.Measure("ProfilerTest", "SelfCostWithoutOp"))
                {
                }
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            using (Profiler.Measure("ProfilerTest", "TotalWithSubMeasures"))
            {
                for (int i = 0; i < iterations; i++)
                {
                    using (Profiler.Measure("ProfilerTest", "DoNothingCall"))
                        DoNothing();
                }
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            using (Profiler.Measure("ProfilerTest", "PureTotal"))
            {
                for (int i = 0; i < iterations; i++)
                {
                    DoNothing();
                }
            }

            foreach (IMeasureItem item in Profiler.GetMeasurementResults("ProfilerTest"))
            {
                Console.WriteLine("{0}: {1:N2} ms", item.Operation, item.TotalTime.TotalMilliseconds);
            }

            Console.WriteLine();
            Console.WriteLine("PureTotal should be nearly the same as Direct measurement, and PureTotal should be DoNothingCall - SelfCostWithoutOp");
            Console.WriteLine("TotalWithSubMeasures - DoNothingCall = the cost of the Profiler itself (SelfCostWithoutOp does not contain the administration costs of the results)");
        }
예제 #11
0
 private static void RunStatic()
 {
     var test = new PerformanceTest();
     Console.WriteLine("Starting Static");
     var stopwatch = Stopwatch.StartNew();
     test.UserToUserModel_StaticMap();
     stopwatch.Stop();
     Console.WriteLine("Static completed in: {0} ms", stopwatch.ElapsedMilliseconds);
 }
예제 #12
0
 protected override void OpenSession()
 {
     context = new PerformanceTest();
 }
예제 #13
0
    private void RunTest(TestType testType, bool RunBaseLine = true)
    {
        PerformanceTest test       = null;
        int             iterations = int.Parse(inputField.text);

        switch (testType)
        {
        case TestType.Exception:
            test = new ExceptionTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Strings:
            test = new StringsTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Arrays:
            test = new ArraysTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Boxing:
            test = new BoxingTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.ForForeach:
            test = new ForForeachTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Struct:
            test = new StructTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Memory:
            test = new MemoryTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Instantiation:
            test = new InstantiationTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Properties:
            test = new PropertiesTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        default:
            throw new ArgumentOutOfRangeException(nameof(testType), testType, null);
        }

        titleText.text       = test.Name;
        descriptionText.text = test.Description;
        var averageResult = test.Measure();

        lastPerformanceResult = averageResult;
        UpdatePerformanceResultUI();

        var(perA, perB, perC) = GetPercentageOfResult(averageResult);
        totalASlider.value    = perA;
        totalBSlider.value    = perB;
        totalCSlider.value    = perC;
    }
예제 #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            PerformanceTest pt = new PerformanceTest();

            pt.SetCount(10000);//设置循环次数
            using (SqlSugarClient db = new SqlSugarClient(System.Configuration.ConfigurationManager.ConnectionStrings["sqlConn"].ToString()))
            {
                var sqlconn = db.GetConnection();

                TuncateTable(db);//清空

                //sqlSuagr
                pt.Execute(i =>
                {
                    db.Insert <Models.InsertTest>(GetData());
                }, m => { }, "sqlSuagr");



                TuncateTable(db);


                //ef4.0+Sql05
                using (TestLib.SqlSugarTestEntities ef = new TestLib.SqlSugarTestEntities())
                {
                    pt.Execute(i =>
                    {
                        ef.InsertTests.AddObject(GetEFData());
                        ef.SaveChanges();
                    }, m => { }, "ef4.0+Sql05");
                }


                TuncateTable(db);

                //dapper
                pt.Execute(i =>
                {
                    sqlconn.Execute("insert into InsertTest (v1,v2,v3,int1,d1,txt ) values(@v1,@v2,@v3,@int1,@d1,@txt);select @@identity;", GetData());
                }, m => { }, "dapper");


                TuncateTable(db);

                //ado.net
                pt.Execute(i =>
                {
                    db.GetScalar("insert into InsertTest (v1,v2,v3,int1,d1,txt ) values(@v1,@v2,@v3,@int1,@d1,@txt);select @@identity;", new SqlParameter[] {
                        new SqlParameter("@d1", DateTime.Now),
                        new SqlParameter("@int1", 11),
                        new SqlParameter("@txt", "哈另一个txt"),
                        new SqlParameter("@v1", "v1sdfasdas"),
                        new SqlParameter("@v2", "v2sdfasfas"),
                        new SqlParameter("@v3", "v3adfasdf"),
                        new SqlParameter("@id", 1)
                    });
                }, m => { }, "ado.net");
            }

            //输出测试页面
            GridView gv = new GridView();

            gv.DataSource = pt.GetChartSource();
            gv.DataBind();
            Form.Controls.Add(gv);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //性能测试类
            PerformanceTest p = new PerformanceTest();

            p.SetCount(100000);        //循环次数(默认:1)
            p.SetIsMultithread(false); //是否启动多线程测试 (默认:false)

            /******************************CreateInstance********************************/
            //带cache
            p.Execute(
                i =>
            {
                CreateInstanceByCache();                  //调用函数
            },
                message => { Response.Write(message); }); //总共执行时间:0.09901秒

            //不带cache
            p.Execute(
                i =>
            {
                CreateInstanceNoCache();                  //调用函数
            },
                message => { Response.Write(message); }); //总共执行时间:0.32002秒


            /******************************ExecuteMethod********************************/
            //带cache
            p.Execute(
                i =>
            {
                ExecuteMethodByCache();                   //调用函数
            },
                message => { Response.Write(message); }); //总共执行时间:0.36202秒

            //不带cache
            p.Execute(
                i =>
            {
                ExecuteMethodNoCache();                   //调用函数
            },
                message => { Response.Write(message); }); //总共执行时间:1.35508秒


            /******************************ExecuteMethod********************************/
            //带cache
            p.Execute(
                i =>
            {
                ExecuteMethodByCache();                   //调用函数
            },
                message => { Response.Write(message); }); //总共执行时间:0.36202秒

            //不带cache
            p.Execute(
                i =>
            {
                ExecuteMethodNoCache();                   //调用函数
            },
                message => { Response.Write(message); }); //总共执行时间:1.35508秒


            /******************************LoadFile********************************/
            //带cache
            p.Execute(
                i =>
            {
                LoadFileByCache();                        //调用函数
            },
                message => { Response.Write(message); }); //总共执行时间:0.11801

            //不带cache
            p.Execute(
                i =>
            {
                LoadFileNoCache();                        //调用函数
            },
                message => { Response.Write(message); }); //总共执行时间:4.89628秒

            //还有其它方法就不测试了
        }
예제 #16
0
 static IQueryable GetAllSimplest(PerformanceTest context)
 {
     return(context.Simplests.Where(s => s.Id > 0));
 }
 private void PerformTests(PerformanceTest performanceTest)
 {
     performanceTest.Perform(_numberOfIterations);
 }
예제 #18
0
        public void FillFormForPosition(string examinationPosition, string examinationNumber, string examinationName, string appleant, string fName, string mName, string lName, string aka,
                                        string lastFourSSN, string contactPhone, string mailingAddress, string city, string state, string zip, string email, string cEmail, string empNumber,
                                        string payroll, string department, string appealIssue, string document, string attachmentDesciption, string remedy
                                        )
        {
            // SubmitAppeal.Clicks();
            BtnIAgree.Clicks();

            PositionHeadingID.Clicks();
            if (examinationPosition == "Application Reject")
            {
                ApplicationRejection.Clicks();
            }
            else if (examinationPosition == "Appraisal of Promotability")
            {
                AppraisalOfPromotability.Clicks();
            }
            else if (examinationPosition == "Evaluation of Training and Experience")
            {
                EvaluationOfTraining.Clicks();
            }
            else if (examinationPosition == "Interview")
            {
                Interview.Clicks();
            }
            else if (examinationPosition == "Performance Test")
            {
                PerformanceTest.Clicks();
            }
            else if (examinationPosition == "Veteran Credit")
            {
                VeteranCredit.Clicks();
            }
            else if (examinationPosition == "Paper-and-Pencil Written Tests")
            {
                WrittenTests.Clicks();
            }
            else if (examinationPosition == "Computer-Administered Tests")
            {
                ComputerAdministeredTests.Clicks();
            }

            ExaminationNumber.SendKeys(examinationNumber);
            ExaminationName.SendKeys(examinationName);
            if (appleant == "Yourself")
            {
                FillingYourSelf.Click();
            }
            FName.EnterText(fName);
            MName.EnterText(mName);
            LName.EnterText(lName);
            Aka.EnterText(aka);
            LastFourSSN.EnterText(lastFourSSN);
            ContactPhone.EnterText(contactPhone);
            MailingAddress.EnterText(mailingAddress);
            City.EnterText(city);
            State.ClearText(state);
            ZipCode.EnterText(zip);
            PreferredEmail.EnterText(email);
            ConfirmEmail.EnterText(cEmail);
            EmployeeNumber.EnterText(empNumber);
            Payroll.EnterText(payroll);
            EmployingDepartment.EnterText(department);
            AppealIssue.EnterText(appealIssue);
            Attach.Clicks();
            Browse.UploadFile(document);
            AttachmentDescription.EnterText(attachmentDesciption);
            Remedy.SendKeys(remedy);
            SubmitBtn.Clicks();
            AcceptPopupBtn.Clicks();
        }
        public void CompareProfilingWaysExpensiveOperation()
        {
            const int iterations = 10000;
            var       test       = new PerformanceTest <int>
            {
                TestName   = "DoTest performance without warm up",
                Iterations = iterations,
                WarmUp     = false,
                Repeat     = 5,
            }
            .AddCase(DoSomething, nameof(DoSomething));

            // 1. DoTest without warmup
            test.DoTest().DumpResults(Console.Out);

            test.TestName = "DoTest performance with warmup";
            test.WarmUp   = true;

            // 2. DoTest with warmup
            test.DoTest().DumpResults(Console.Out);

            // 3. Direct test
            Console.WriteLine("===========Direct measurement test===============");
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            // warming up
            for (int i = 0; i < iterations; i++)
            {
                DoSomething();
            }

            Stopwatch watch = new Stopwatch();

            watch.Start();
            for (int i = 0; i < iterations; i++)
            {
                DoSomething();
            }

            watch.Stop();
            Console.WriteLine("Total Time: {0:N2} ms", watch.Elapsed.TotalMilliseconds);
            Console.WriteLine();

            // 4. Profiler test
            Console.WriteLine("===========Profiler test===============");
            Profiler.AutoSaveResults = false;
            Profiler.Reset();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            for (int i = 0; i < iterations; i++)
            {
                using (Profiler.Measure("ProfilerTest", "WarmingUp"))
                {
                }
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            for (int i = 0; i < iterations; i++)
            {
                using (Profiler.Measure("ProfilerTest", "SelfCostWithoutOp"))
                {
                }
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            using (Profiler.Measure("ProfilerTest", "TotalWithSubMeasures"))
            {
                for (int i = 0; i < iterations; i++)
                {
                    using (Profiler.Measure("ProfilerTest", "DoSomethingCall"))
                        DoSomething();
                }
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            using (Profiler.Measure("ProfilerTest", "PureTotal"))
            {
                for (int i = 0; i < iterations; i++)
                {
                    DoSomething();
                }
            }

            foreach (IMeasureItem item in Profiler.GetMeasurementResults("ProfilerTest"))
            {
                Console.WriteLine("{0}: {1:N2} ms", item.Operation, item.TotalTime.TotalMilliseconds);
            }

            Console.WriteLine();
            Console.WriteLine("In case of a costly operation the DirectTotal < PureTotal < DoTest < DoSomethingCall < TotalWithSubMeasures should have nearly the same value.");
        }
예제 #20
0
        /**
         * Entry point of program
         */
        public static void Main(string[] args)
        {
            Console.WriteLine("Running QueryProcessor. Press Enter to exit...");

            if (args.Length != 1)
            {
                Console.WriteLine("Usage: soccer.exe <domain-id>");
                return;
            }
            else
            {
                DefaultParticipant.DomainId = Int32.Parse(args[0]);
            }

            try
            {
                //initialize player information
                MetaData.initializePlayerData();

                //create Sensor mapping to player name
                MetaData.createSensorMap();

                //create Player mapping to sensor_ids
                MetaData.createPlayerMap();

                //create Player mapping to team_ids
                MetaData.createTeamMap();

                //get an instance of default domain participant
                DDS.DomainParticipant participant = DefaultParticipant.Instance;

                //Register types that will be used in application
                registerTypes();

                Soccer prog = new Soccer();
                //initialize dataWriters
                prog.initializeDataWriters();

                IDisposable disposable = null;
                Console.WriteLine("******************Initialization is Complete**************");

                //eventInfoStream subject is used to convey intermediate output from query-2 to query-4
                var eventInfoStream = new Subject <BallPossessionQuery.EventInfo>();
                //heatMapSub subject is used to integrate HeatMap data for 17*4=68 streams. (17 players * 4 grid types)
                var heatMapSub = new Subject <HeatMapProcessor.HeatMapData>();

                //create rawSensorStream from data received on DDS topic "Raw SensorData"
                DDS.Duration_t timeout;
                timeout.nanosec = 0;
                timeout.sec     = 10;

                /*var dict =
                 *  MetaData.PLAYER_MAP
                 *      .SelectMany((KeyValuePair<string, List<int>> keyValue, int index) =>
                 *       {
                 *           return keyValue.Value;
                 *       })
                 *      .ToDictionary(sensor_id => sensor_id,
                 *                    sensor_id => new DDSKeyedSubject<int, SensorData>(sensor_id));
                 */
                IObservable <SensorData> rawSensorStream = DDSObservable
                                                           .FromTopicWaitSet <SensorData>(participant, "Raw SensorData", timeout);

                /*IObservable<IGroupedObservable<int, SensorData>> rawSensorStream = DDSObservable
                 *  .FromKeyedTopicWaitSet<int, SensorData>(
                 *          participant,
                 *          "Raw SensorData",
                 *          (sensor) => sensor.sensor_id,
                 *          dict,
                 *          timeout);*/

                //used to keep track of number of output samples produced from a query.
                int output_count = 0;

                //initialize PerformanceTest.ptArray that stores a PerformanceTest obj for each player stream
                PerformanceTest.initializePtArr();
                //set AvgProcessorStatus equal to true to compute performance metrics for AverageProcessor.
                PerformanceTest.AvgProcessorStatus = false;
                PerformanceTest.CurrRunningStatus  = false;
                PerformanceTest.AggRunningStatus   = true;

                //start throughput timer before query
                PerformanceTest.startThroughputSW();
                int input_count   = 0;
                var countedStream =
                    rawSensorStream.Do(data => ++ input_count)
                    .Publish();


                //query-1 AverageProcessor

                /*disposable= countedStream
                 *   //.ObserveOn(new EventLoopScheduler())
                 *   .averageProcessor()
                 *   .Merge()
                 *   //if PerformanceTest.AvgProcessorStatus is true, then perform Do side-effect.
                 *   .DoIf(() => PerformanceTest.AvgProcessorStatus,
                 *       d => output_count++,
                 *       () =>
                 *       {
                 *         if (PerformanceTest.AvgProcessorStatus)
                 *         {
                 *           PerformanceTest.postProcess("averageProcessor_stats.txt");
                 *           Console.WriteLine("Inputs = {0}. Output count = {1} ", input_count, output_count);
                 *         }
                 *       })
                 *   //.Subscribe(prog.mPlayerDataWriter);
                 *     .Subscribe();*/

                //Query-1 CurrentRunningProcessor

                /*disposable = countedStream.Average()
                 *                        .CurrentRunningAnalysis()
                 *                        .Merge()
                 *                      //.Subscribe(prog.mCurrentRunningDataWriter);
                 *                        .Subscribe();*/

                //Query-1 AggregateRunningProcessor
                disposable = countedStream.Average()
                             //disposable = AverageProcessor.Average(dict)
                             .CurrentRunningAnalysis()
                             .FullGameAggregateRunningDataAnalysis()
                             .Merge()
                             .DoIf(() => PerformanceTest.AggRunningStatus,
                                   d => output_count++,
                                   () =>
                {
                    if (PerformanceTest.AggRunningStatus)
                    {
                        PerformanceTest.postProcess("AggRunning_stats.txt");
                        Console.WriteLine("Inputs = {0}. Output count = {1} ", input_count, output_count);
                    }
                })
                             .Subscribe();

                //Query2
                //disposable= countedStream.ballPossessionProcessor(ref eventInfoStream).Subscribe(prog.mPlayerBallPossessionDataWriter);

                /*//Query3
                 * countedStream.averageProcessor().heatMapProcessor(heatMapSub);
                 * disposable= heatMapSub.Subscribe();*/

                //Query4
                //disposable= countedStream.shotOnGoalProcessor(ref eventInfoStream).Subscribe(prog.mshotOnGoalDataWriter);

                countedStream.Connect();
                //rawSensorStream.Subscribe();
                Console.ReadLine();


                while (disposable != null)
                {
                    ConsoleKeyInfo info = Console.ReadKey(true);
                    if (info.Key == ConsoleKey.Enter)
                    {
                        disposable.Dispose();
                        break;
                    }
                }
            }
            catch (DDS.Exception e)
            {
                Console.WriteLine("Error: {0}", e);
            }
            Console.WriteLine("Quitting...");
            DefaultParticipant.Shutdown();
        }
예제 #21
0
 private static void RunAutoReused()
 {
     var test = new PerformanceTest();
     Console.WriteLine("Starting AutoMap_Reused");
     var stopwatch = Stopwatch.StartNew();
     test.UserToUserModel_AutoMap_Reused();
     stopwatch.Stop();
     Console.WriteLine("AutoMap_Reused completed in: {0} ms", stopwatch.ElapsedMilliseconds);
 }