Example #1
1
        private void AsymmetricObjects()
        {
            Console.WriteLine("Asymmetric");
            Console.WriteLine("----------");

            // bind
            var numberBinding = new Binding("Number") {Source = _guineaPig};
            var nameBinding = new Binding("FullName") {Source = _guineaPig};
            _subjectUnderTest.Number.SetBinding(System.Windows.Controls.TextBox.TextProperty, numberBinding);
            _subjectUnderTest.FullName.SetBinding(System.Windows.Controls.TextBox.TextProperty, nameBinding);

            var testDuration = new Stopwatch();
            testDuration.Start();
            RunAsymmetric();
            testDuration.Stop();
            Console.WriteLine(
                string.Format("Write to {0}: {1} msec.", _subjectUnderTest.GetType().Name, testDuration.ElapsedMilliseconds.ToString("#,###")));

            testDuration.Restart();
            RunReverseAsymmetric();
            testDuration.Stop();
            Console.WriteLine(
                string.Format("Write to {0}: {1} msec.", _guineaPig.GetType().Name, testDuration.ElapsedMilliseconds.ToString("#,###")));

            Console.WriteLine();
        }
Example #2
0
		public static void run(Action testMethod, int rounds){
			Stopwatch stopwatch = new Stopwatch();
			stopwatch.Reset();
			stopwatch.Start();
			while (stopwatch.ElapsedMilliseconds < 1200)  // A Warmup of 1000-1500 mS 
				// stabilizes the CPU cache and pipeline.
			{
				testMethod(); // Warmup
				clearMemory ();
			}
			stopwatch.Stop();
			long totalmem;
			Console.WriteLine ("Round;Runtime ms;Memory KB");
			for (int repeat = 0; repeat < rounds; ++repeat)
			{
				stopwatch.Reset();
				stopwatch.Start();
				testMethod();
				stopwatch.Stop();
				totalmem = getUsedMemoryKB ();
				clearMemory ();
				Console.WriteLine((1+repeat)+";"+stopwatch.ElapsedMilliseconds + ";"
					+totalmem);
			}
		}
Example #3
0
    public static void Main()
    {
        Stopwatch watch = new Stopwatch();
        Random rand = new Random();
        watch.Start();
        for (int i = 0; i < iterations; i++)
            DayOfYear1(rand.Next(1, 13), rand.Next(1, 29));
        watch.Stop();
        Console.WriteLine("Local array: " + watch.Elapsed);
        watch.Reset();
        watch.Start();
        for (int i = 0; i < iterations; i++)
            DayOfYear2(rand.Next(1, 13), rand.Next(1, 29));
        watch.Stop();
        Console.WriteLine("Static array: " + watch.Elapsed);

        // trying to modify static int []
        daysCumulativeDays[0] = 18;
        foreach (int days in daysCumulativeDays)
        {
            Console.Write("{0}, ", days);
        }
        Console.WriteLine("");

        // MY_STR_CONST = "NOT CONST";
    }
Example #4
0
        public void should_be_within_performace_tolerance()
        {
            var xml = File.ReadAllText("model.json").ParseJson();
            var json = JElement.Load(File.ReadAllBytes("model.json"));
            var stopwatch = new Stopwatch();

            var controlBenchmark = Enumerable.Range(1, 1000).Select(x =>
            {
                stopwatch.Restart();
                xml.EncodeJson();
                stopwatch.Stop();
                return stopwatch.ElapsedTicks;
            }).Skip(5).Average();

            var flexoBenchmark = Enumerable.Range(1, 1000).Select(x =>
            {
                stopwatch.Restart();
                json.Encode();
                stopwatch.Stop();
                return stopwatch.ElapsedTicks;
            }).Skip(5).Average();

            Console.Write("Control: {0}, Flexo: {1}", controlBenchmark, flexoBenchmark);

            flexoBenchmark.ShouldBeLessThan(controlBenchmark * 5);
        }
Example #5
0
		public void ECPerformanceTest()
		{
			Stopwatch sw = new Stopwatch();
			int timesofTest = 1000;
			
			string[] timeElapsed = new string[2];
			string testCase = "sdg;alwsetuo1204985lkscvzlkjt;";
			sw.Start();
			
			for(int i = 0; i < timesofTest; i++)
			{
				this.Encode(testCase, 3);
			}
			
			sw.Stop();
			
			timeElapsed[0] = sw.ElapsedMilliseconds.ToString();
			
			sw.Reset();
			
			sw.Start();
			
			for(int i = 0; i < timesofTest; i++)
			{
				this.ZXEncode(testCase, 3);
			}
			sw.Stop();
			
			timeElapsed[1] = sw.ElapsedMilliseconds.ToString();
			
			
			Assert.Pass("EC performance {0} Tests~ QrCode.Net: {1} ZXing: {2}", timesofTest, timeElapsed[0], timeElapsed[1]);
			
		}
Example #6
0
        private void btnInterpretate_Click(object sender, EventArgs e)
        {
            try
            {

                Stopwatch timer = new Stopwatch();
                RegularExpression r;

                timer.Reset();
                timer.Start();
                r = new RegularExpression(txtRegEx.Text);
                timer.Stop();
                ReportResult("Parsing '" + txtRegEx.Text + "'", "SUCCESS", r.IsCompiled, timer);

                timer.Reset();
                timer.Start();
                bool result = r.IsMatch(txtInput.Text);
                timer.Stop();
                ReportResult("Matching '" + txtInput.Text + "'", result.ToString(), r.IsCompiled, timer);

                ReportData("Original Expression:\t" + r.OriginalExpression + "\r\nInfix Expression:\t" + r.FormattedExpression + "\r\nPostfix string:\t" + r.PostfixExpression + "\r\n\r\nNon Deterministic Automata has\t\t" + r.NDStateCount + " states.\r\nDeterministic Automata has\t\t" + r.DStateCount + " states.\r\nOptimized Deterministic Automata has\t" + r.OptimizedDStateCount + " states.");

                automataViewer1.Initialize(r);
            }
            catch (RegularExpressionParser.RegularExpressionParserException exc)
            {
                ReportError("PARSER ERROR", exc.ToString());
            }
            catch (Exception exc)
            {
                ReportError("EXCEPTION", exc.ToString());
            }
        }
        public static void BackSequentialCompare(int countOfElementInArray)
        {
            int[] intArray = new int[countOfElementInArray];
            double[] doubleArray = new double[countOfElementInArray];
            string[] stringArray = new string[countOfElementInArray];

            for (int i = countOfElementInArray - 1; i >= 0; i--)
            {
                intArray[i] = i;
                doubleArray[i] = i;
                stringArray[i] = i.ToString();
            }

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Restart();
            QuickSort<int>.Sort(intArray, Comparer<int>.Default);
            stopwatch.Stop();

            Console.WriteLine("Quick sort result for back sequential int is:{0}", stopwatch.ElapsedMilliseconds);

            stopwatch.Restart();
            QuickSort<double>.Sort(doubleArray, Comparer<double>.Default);
            stopwatch.Stop();

            Console.WriteLine("Quick sort result for back sequential double is:{0}", stopwatch.ElapsedMilliseconds);

            stopwatch.Restart();
            QuickSort<string>.Sort(stringArray, Comparer<string>.Default);
            stopwatch.Stop();

            Console.WriteLine("Quick sort result for back sequential string is:{0}", stopwatch.ElapsedMilliseconds);
        }
Example #8
0
        private static void RunWithContext(string topic, int iterations, Federation federation)
        {
            using (RequestContext.Create())
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                string content = federation.GetTopicFormattedContent(new QualifiedTopicRevision(topic), null);
                stopwatch.Stop();

                Console.WriteLine("Rendered first times in {0} seconds", stopwatch.ElapsedMilliseconds / 1000.0F);

                stopwatch.Reset();
                stopwatch.Start();
                content = federation.GetTopicFormattedContent(new QualifiedTopicRevision(topic), null);
                stopwatch.Stop();

                Console.WriteLine("Rendered second time in {0} seconds", stopwatch.ElapsedMilliseconds / 1000.0F);

                stopwatch.Reset();
                stopwatch.Start();
                content = federation.GetTopicFormattedContent(new QualifiedTopicRevision(topic), null);
                stopwatch.Stop();

                Console.WriteLine("Rendered third time in {0} seconds", stopwatch.ElapsedMilliseconds / 1000.0F);
            }
        }
Example #9
0
        public void TestCutLargeFile()
        {
            var weiCheng = File.ReadAllText(@"Resources\围城.txt");
            var seg = new JiebaSegmenter();
            seg.Cut("热身");

            Console.WriteLine("Start to cut");
            var n = 20;
            var stopWatch = new Stopwatch();

            // Accurate mode
            stopWatch.Start();

            for (var i = 0; i < n; i++)
            {
                seg.Cut(weiCheng);
            }
            
            stopWatch.Stop();
            Console.WriteLine("Accurate mode: {0} ms", stopWatch.ElapsedMilliseconds / n);

            // Full mode
            stopWatch.Reset();
            stopWatch.Start();

            for (var i = 0; i < n; i++)
            {
                seg.Cut(weiCheng, true);
            }

            stopWatch.Stop();
            Console.WriteLine("Full mode: {0} ms", stopWatch.ElapsedMilliseconds / n);
        }
Example #10
0
        public void Test_perf_of_query_without_index()
        {
            OdbFactory.Delete("index1perf.ndb");
            using (var odb = OdbFactory.Open("index1perf.ndb"))
            {
                for (var i = 0; i < 5000; i++)
                {
                    var player = new Player("Player" + i, DateTime.Now, new Sport("Sport" + i));
                    odb.Store(player);
                }
            }

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            using (var odb = OdbFactory.OpenLast())
            {
                var query = odb.Query<Player>();
                query.Descend("Name").Constrain((object) "Player20").Equal();
                var count = query.Execute<Player>().Count;
                Assert.That(count, Is.EqualTo(1));
            }
            stopwatch.Stop();
            Console.WriteLine("Elapsed {0} ms", stopwatch.ElapsedMilliseconds);

            stopwatch.Reset();
            stopwatch.Start();
            using (var odb = OdbFactory.OpenLast())
            {
                var query = odb.Query<Player>();
                query.Descend("Name").Constrain((object) "Player1234").Equal();
                var count = query.Execute<Player>().Count;
                Assert.That(count, Is.EqualTo(1));
            }
            stopwatch.Stop();
            Console.WriteLine("Elapsed {0} ms", stopwatch.ElapsedMilliseconds);

            stopwatch.Reset();
            stopwatch.Start();
            using (var odb = OdbFactory.OpenLast())
            {
                var query = odb.Query<Player>();
                query.Descend("Name").Constrain((object) "Player4444").Equal();
                var count = query.Execute<Player>().Count;
                Assert.That(count, Is.EqualTo(1));
            }
            stopwatch.Stop();
            Console.WriteLine("Elapsed {0} ms", stopwatch.ElapsedMilliseconds);

            stopwatch.Reset();
            stopwatch.Start();
            using (var odb = OdbFactory.OpenLast())
            {
                var query = odb.Query<Player>();
                query.Descend("Name").Constrain((object) "Player3211").Equal();
                var count = query.Execute<Player>().Count;
                Assert.That(count, Is.EqualTo(1));
            }
            stopwatch.Stop();
            Console.WriteLine("Elapsed {0} ms", stopwatch.ElapsedMilliseconds);
        }
Example #11
0
        private int FindAndSaveApps(ICollection<int> partition) {
            ICollection<App> apps = appParser.RetrieveApps(partition);

            if (apps == null) {
                return 0;
            }

            Stopwatch watch = new Stopwatch();
            watch.Start();

            foreach (App app in apps) {
                repository.App.Save(app);

                indexer.AddApp(app);
            }

            watch.Stop();
            logger.Debug("Saved {0} apps using {1}ms", apps.Count, watch.ElapsedMilliseconds);

            watch.Reset();
            watch.Start();

            indexer.Flush();

            watch.Stop();
            logger.Debug("Indexed {0} apps using {1}ms", apps.Count, watch.ElapsedMilliseconds);

            return apps.Count;
        }
        public void WillWaitForItem() {
            using (var queue = GetQueue()) {
                queue.DeleteQueue();

                TimeSpan timeToWait = TimeSpan.FromSeconds(1);
                var sw = new Stopwatch();
                sw.Start();
                var workItem = queue.Dequeue(timeToWait);
                sw.Stop();
                Trace.WriteLine(sw.Elapsed);
                Assert.Null(workItem);
                Assert.True(sw.Elapsed > timeToWait.Subtract(TimeSpan.FromMilliseconds(10)));

                Task.Factory.StartNewDelayed(100, () => queue.Enqueue(new SimpleWorkItem {
                    Data = "Hello"
                }));

                sw.Reset();
                sw.Start();
                workItem = queue.Dequeue(timeToWait);
                workItem.Complete();
                sw.Stop();
                Trace.WriteLine(sw.Elapsed);
                Assert.NotNull(workItem);
            }
        }
Example #13
0
    // Use this for initialization
    void Start()
    {
        if (SVGFile != null) {
          Stopwatch w = new Stopwatch();

          w.Reset();
          w.Start();
          ISVGDevice device;
          if(useFastButBloatedRenderer)
        device = new SVGDeviceFast();
          else
        device = new SVGDeviceSmall();
          m_implement = new Implement(this.SVGFile, device);
          w.Stop();
          long c = w.ElapsedMilliseconds;

          w.Reset();
          w.Start();
          m_implement.StartProcess();
          w.Stop();
          long p = w.ElapsedMilliseconds;

          w.Reset();
          w.Start();
          renderer.material.mainTexture = m_implement.GetTexture();
          w.Stop();
          long r = w.ElapsedMilliseconds;
          UnityEngine.Debug.Log("Construction: " + Format(c) + ", Processing: " + Format(p) + ", Rendering: " + Format(r));

          Vector2 ts = renderer.material.mainTextureScale;
          ts.x *= -1;
          renderer.material.mainTextureScale = ts;
          renderer.material.mainTexture.filterMode = FilterMode.Trilinear;
        }
    }
Example #14
0
        public void BinaryStressTest()
        {
            var b = new Truck("MAN");

            var upper = Math.Pow(10, 3);

            var sw = new Stopwatch();

            sw.Start();

            b.LoadCargo(BinaryTestModels.ToList());

            sw.Stop();

            var secondElapsedToAdd = sw.ElapsedMilliseconds;

            Trace.WriteLine(string.Format("Put on the Channel {1} items. Time Elapsed: {0}", secondElapsedToAdd, upper));
            sw.Reset();
            sw.Start();

            b.DeliverTo("Dad");
            sw.Stop();

            var secondElapsedToBroadcast = sw.ElapsedMilliseconds ;

            Trace.WriteLine(string.Format("Broadcast on the Channel {1} items. Time Elapsed: {0}", secondElapsedToBroadcast, upper));

            var elem = b.UnStuffCargo<List<BinaryTestModel>>().First();

            Assert.AreEqual(elem.Count(), 1000, "Not every elements have been broadcasted");
            Assert.IsTrue(secondElapsedToAdd < 5000, "Add took more than 5 second. Review the logic, performance must be 10000 elems in less than 5 sec");
            Assert.IsTrue(secondElapsedToBroadcast < 3000, "Broadcast took more than 3 second. Review the logic, performance must be 10000 elems in less than 5 sec");
        }
Example #15
0
        public void CopyConstructorSpeed()
        {
            var random = new Random();

            var values = new double[5000000];
            for (var i = 0; i < 5000000; i++)
            {
                values[i] = random.Next();
            }

            var scalarSet = new ScalarSet(values);

            // copying values
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            values.Clone();
            stopwatch.Stop();

            var copyArrayTime = stopwatch.ElapsedMilliseconds;
            Trace.WriteLine("Copying array with 1M values took: " + copyArrayTime + " ms");

            stopwatch.Reset();
            stopwatch.Start();
            new ScalarSet(scalarSet);
            stopwatch.Stop();

            Trace.WriteLine("Copying scalar set with 1M values took: " + stopwatch.ElapsedMilliseconds + " ms");

            var fraction = stopwatch.ElapsedMilliseconds/copyArrayTime;

            Assert.IsTrue(fraction < 1.1);
        }
        public async Task When_bandwidth_is_applied_then_time_to_receive_data_should_be_longer_for_multiple_requests()
        {
            int bandwidth = -1;
            // ReSharper disable once AccessToModifiedClosure - yeah we want to modify it...
            Func<int> getMaxBandwidth = () => bandwidth;

            var stopwatch = new Stopwatch();
            using (HttpClient httpClient = CreateHttpClient(getMaxBandwidth, 1))
            {
                stopwatch.Start();

                await httpClient.GetAsync("/");
                await httpClient.GetAsync("/");

                stopwatch.Stop();
            }
            TimeSpan nolimitTimeSpan = stopwatch.Elapsed;

            bandwidth = 1000;
            using (HttpClient httpClient = CreateHttpClient(getMaxBandwidth, 1))
            {
                stopwatch.Restart();

                await httpClient.GetAsync("/");
                await httpClient.GetAsync("/");

                stopwatch.Stop();
            }
            TimeSpan limitedTimeSpan = stopwatch.Elapsed;

            Console.WriteLine(nolimitTimeSpan);
            Console.WriteLine(limitedTimeSpan);

            limitedTimeSpan.Should().BeGreaterThan(nolimitTimeSpan);
        }
Example #17
0
        static void Main()
        {
            OrderedBag<Product> products = new OrderedBag<Product>();

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            for (int i = 1; i < 500000; i++)
            {
                Product p = new Product();
                p.Name = "Prodcut" + i;
                p.Price = GetRandomNumber(35, 599) * i * GetRandomNumber(3, 5) / GetRandomNumber(2, 4);
                products.Add(p);
            }

            stopwatch.Stop();
            Console.WriteLine("Create and Add 500k products: {0}", stopwatch.Elapsed);

            List<Product> prodRange = new List<Product>();
            stopwatch.Reset();
            stopwatch.Restart();

            for (int i = 1; i <= 10000; i++)
            {
                int min = GetRandomNumber(35, 599) * i * GetRandomNumber(3, 5) / GetRandomNumber(2, 4);
                int max = GetRandomNumber(35, 599) * i * 13 * GetRandomNumber(3, 5);

                prodRange.AddRange(products.Range(new Product() { Price = min }, true, new Product() { Price = max }, true).Take(20));
            }

            stopwatch.Stop();
            Console.WriteLine("Search for 10k random price ranges: {0}", stopwatch.Elapsed);
        }
Example #18
0
        static void TestSine(float floatTester, double doubleTester, decimal decimalTester)
        {
            Stopwatch stopwatch = new Stopwatch();

            Console.WriteLine("Testing Sine :\n-------------------------------- ");
            stopwatch.Start();
            for (float i = 0; i < 1000; i++)
            {
                floatTester = (float)Math.Sin(floatTester);
            }
            stopwatch.Stop();
            Console.WriteLine("Float:   {0,20}", stopwatch.Elapsed);
            stopwatch.Restart();

            for (double i = 0; i < 1000; i++)
            {
                doubleTester = Math.Sin(doubleTester);
            }
            stopwatch.Stop();
            Console.WriteLine("Double:  {0,20}", stopwatch.Elapsed);
            stopwatch.Restart();

            for (decimal i = 0; i < 1000; i++)
            {
                decimalTester = (decimal)Math.Sin((double)decimalTester);
            }
            stopwatch.Stop();
            Console.WriteLine("Decimal: {0,20}", stopwatch.Elapsed);
        }
Example #19
0
 /// <summary>
 /// StringMap3
 /// </summary>
 private static void benchmark9(int size)
 {
     GC.Collect();
     var dictionary = new StringMap3<int>();
     var keys = new string[size];
     for (int i = 0; i < keys.Length; i++)
         keys[i] = i.ToString();
     var sw = new Stopwatch();
     sw.Start();
     for (int i = 0; i < keys.Length; i++)
         dictionary.Add(keys[(long)i * psrandmul % keys.Length], (int)(((long)i * psrandmul) % keys.Length));
     sw.Stop();
     Console.WriteLine(sw.Elapsed);
     GC.GetTotalMemory(true);
     sw.Restart();
     foreach (var t in dictionary)
     {
         // System.Diagnostics.Debugger.Break(); // порядок не соблюдается. Проверка бессмыслена
     }
     sw.Stop();
     Console.WriteLine(sw.Elapsed);
     GC.GetTotalMemory(true);
     sw.Restart();
     for (int i = 0; i < keys.Length; i++)
     {
         if (dictionary[keys[i]] != i)
             throw new Exception();
     }
     sw.Stop();
     Console.WriteLine(sw.Elapsed);
 }
        internal static void Main()
        {
            var stopwatch = new Stopwatch();
            var context = new TelerikAcademyEntities();
            stopwatch.Start();
            var employees = context.Employees;
            foreach (var employee in employees)
            {
                Console.WriteLine(
                    "{0}, {1}, {2}",
                    (employee.FirstName + ' ' + employee.LastName).PadLeft(30),
                    employee.Department.Name.PadLeft(30),
                    employee.Address.Town.Name.PadLeft(15));
            }

            stopwatch.Stop();
            Console.WriteLine("Time elapsed: {0} seconds", (decimal)stopwatch.Elapsed.Milliseconds / 1000);

            stopwatch.Reset();
            stopwatch.Start();
            var includeEmployees = context.Employees.Include("Address").Include("Department");
            foreach (var employee in includeEmployees)
            {
                Console.WriteLine(
                    "{0}, {1}, {2}",
                    (employee.FirstName + ' ' + employee.LastName).PadLeft(30),
                    employee.Department.Name.PadLeft(30),
                    employee.Address.Town.Name.PadLeft(15));
            }

            stopwatch.Stop();
            Console.WriteLine("Time elapsed: {0} seconds", (decimal)stopwatch.Elapsed.Milliseconds / 1000);
        }
Example #21
0
        static void Main(string[] args)
        {
            Bootstrapper bootstrapper = Bootstrapper.Create()
                .RegisterInstaller(new ResourceBuilderInstaller())
                .RegisterInstaller(new StructInstaller())
                .RegisterInstaller(new ServiceInstaller());

            string chittinKeyPath = Path.Combine(@"C:\Program Files (x86)\Baldur's Gate Enhanced Edition\Data\00766", "CHITIN.KEY");
            string dialogPath = Path.Combine(@"C:\Program Files (x86)\Baldur's Gate Enhanced Edition\Data\data\lang\en_US", "dialog.tlk");

            var resourceFileProvider = bootstrapper.WindsorContainer.Resolve<IResourceFileProvider>();
            byte[] contentOfFile = resourceFileProvider.GetByteContentOfFile(chittinKeyPath);

            IKeyResourceBuilder keyResourceBuilder = bootstrapper.WindsorContainer.Resolve<IKeyResourceBuilder>();
            //IDlgResourceBuilder dlgResourceBuilder = bootstrapper.WindsorContainer.Resolve<IDlgResourceBuilder>();

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            KeyResource keyResource = keyResourceBuilder.BuildKeyResource(contentOfFile);
            stopwatch.Stop();
            Console.WriteLine("Miliseconds : {0} - Ticks {1}", stopwatch.ElapsedMilliseconds, stopwatch.ElapsedTicks);

            stopwatch.Reset();

            stopwatch.Start();
            KeyResource buildKeyResourceNew = keyResourceBuilder.BuildKeyResourceNew(contentOfFile);
            stopwatch.Stop();
            Console.WriteLine("Miliseconds : {0} - Ticks {1}", stopwatch.ElapsedMilliseconds, stopwatch.ElapsedTicks);

            Console.ReadLine();
        }
        private RoundTripPerformance MakeBltRoundTrip(LNode[] Nodes)
        {
            using (var memStream = new MemoryStream())
            {
                var timer = new Stopwatch();
                timer.Start();

                var writer = new LoycBinaryWriter(memStream);

                for (int i = 0; i < TimedRoundTripCount; i++)
                {
                    writer.WriteFile(Nodes);
                    memStream.Seek(0, SeekOrigin.Begin);
                }

                timer.Stop();
                var writePerf = timer.Elapsed;
                long size = memStream.Length;
                timer.Restart();

                for (int i = 0; i < TimedRoundTripCount; i++)
                {
                    var reader = new LoycBinaryReader(memStream);
                    reader.ReadFile("test.blt");
                    memStream.Seek(0, SeekOrigin.Begin);
                }

                timer.Stop();
                var readPerf = timer.Elapsed;

                return new RoundTripPerformance(readPerf, writePerf, size);
            }
        }
Example #23
0
 private void Form1_Load(object sender, EventArgs e)
 {
     asdassd.Add("MenuGetir", () => new MyClass());
     Stopwatch sw = new Stopwatch();
     sw.Start();
     for (int i = 0; i < 1000000; i++)
     {
         MyClass c = new MyClass();
     }
     sw.Stop();
     MessageBox.Show(sw.ElapsedMilliseconds.ToString());
     sw.Reset();
     Type t = typeof(MyClass);
     sw.Start();
     for (int i = 0; i < 1000000; i++)
     {
         var c = System.Activator.CreateInstance(Type.GetType(t.FullName));
     }
     sw.Stop();
     MessageBox.Show(sw.ElapsedMilliseconds.ToString());
     sw.Reset();
     sw.Start();
     for (int i = 0; i < 1000000; i++)
     {
         var c = asdassd["MenuGetir"]();
     }
     sw.Stop();
     MessageBox.Show(sw.ElapsedMilliseconds.ToString());
 }
Example #24
0
File: F.cs Project: agnet/st12
        public static void TestProgram()
        {
            var sw = new Stopwatch();

            sw.Start();
            Console.WriteLine("Fi(30) = {0} - slow", CalculateNthFi(30));
            sw.Stop();
            Console.WriteLine("Calculated in {0}", sw.ElapsedMilliseconds);

            sw.Reset();

            sw.Start();
            Console.WriteLine("Fi(30) = {0} - fast", CalculateNthFi2(30));
            sw.Stop();
            Console.WriteLine("Calculated in {0}", sw.ElapsedMilliseconds);

            sw.Reset();

            sw.Start();
            Console.WriteLine("Fi(30) = {0} - fast2", CalculateNthFi3(30, 0, 1, 1));
            sw.Stop();
            Console.WriteLine("Calculated in {0}", sw.ElapsedMilliseconds);

            Console.WriteLine("");
        }
        public static void Main()
        {
            var telerikAcademy = new TelerikAcademyEntities();

            telerikAcademy.Departments.Count();

            var stringBuilder = new StringBuilder();

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            var withoutInclude = telerikAcademy.Employees;
            UseTheData(stringBuilder, withoutInclude);

            stopwatch.Stop();
            var firstResult = stopwatch.Elapsed.ToString();

            stopwatch.Restart();

            var withInclude = telerikAcademy.Employees.Include("Department").Include("Address.Town");
            var resultWithInclude = UseTheData(stringBuilder, withInclude);
            stopwatch.Stop();
            var secondResult = stopwatch.Elapsed.ToString();

            Console.WriteLine(resultWithInclude);
            Console.WriteLine("Time without include: {0}", firstResult);
            Console.WriteLine("Time with include: {0}", secondResult);
        }
Example #26
0
        static void PerfCheck()
        {
            CustomMessagesCompare.SomeExtMessage msg = new CustomMessagesCompare.SomeExtMessage()
            {
                field1 = 111,
                field2 = 15
            };

            Dictionary<string, object> a = msg.GetHolder();

            TaskQueue.TQItemSelector sel = new TaskQueue.TQItemSelector
                ("field1", TaskQueue.TQItemSelectorSet.Ascending)
                .Rule("field2", 15L, true);

            Stopwatch watch = new Stopwatch();
            TaskQueue.Providers.TaskMessage.InternalCheckDictionary chk =
                (TaskQueue.Providers.TaskMessage.InternalCheckDictionary)
                TaskQueue.Providers.TaskMessage.MakeCheckerDictionary(sel);
            watch.Start();
            for (int i = 0; i < 1000000; i++)
            {
                chk(a);
            }
            watch.Stop();
            Console.WriteLine("compiled {0:.00}ms", watch.Elapsed.TotalMilliseconds);
            watch.Restart();
            for (int i = 0; i < 1000000; i++)
            {
                TaskQueue.Providers.TaskMessage.CheckWithSelector(a, sel);
            }
            watch.Stop();
            Console.WriteLine("native {0:.00}ms", watch.Elapsed.TotalMilliseconds);
        }
Example #27
0
 public void ComputeTimesPrimes()
 {
     Stopwatch w = new Stopwatch();
     w.Start();
     PrimeNumbers.GeneratePrimeNumbers1(100000);
     Console.WriteLine("Primes 1: " + w.ElapsedMilliseconds.ToString());
     w.Stop();
     w.Reset();
     w.Start();
     PrimeNumbers.GeneratePrimeNumbers2(100000);
     Console.WriteLine("Primes 2: "+ w.ElapsedMilliseconds.ToString());
     w.Stop();
     w.Reset();
     w.Start();
     PrimeNumbers.GeneratePrimeNumbers3(100000);
     Console.WriteLine("Primes 3: " + w.ElapsedMilliseconds.ToString());
     w.Stop();
     w.Start();
     for (int i = 1; i <= 100000; i++)
     {
         int mod = i % 2;
     }
     w.Stop();
     Console.WriteLine("Primes 4: " + w.ElapsedMilliseconds.ToString());
 }
Example #28
0
        String[] GetStatsResultsFromUrl(string url)
        {
            string[] results = new string[2];
            TimeSpan timeTaken;

            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();

            try
            {
                HttpWebRequest req = GetWebRequest(url);
                WebResponse resp = req.GetResponse();
                Stream respStream = resp.GetResponseStream();
                StreamReader sreader = new StreamReader(respStream);
                string xmlfile = sreader.ReadToEnd();
                sreader.Close();
                resp.Close();

                stopWatch.Stop();
                //Non200Responses
                results[0] = "Non200Responses:0";
            }
            catch (System.Net.WebException webExc)
            {
                stopWatch.Stop();
                //Non200Responses
                results[0] = "Non200Responses:" + ((int)((HttpWebResponse)webExc.Response).StatusCode).ToString();
            }

            timeTaken = stopWatch.Elapsed;
            //ResponseTime in Milliseconds            
            results[1] = "ResponseTime:" + Math.Round(timeTaken.TotalMilliseconds).ToString();

            return results;
        }
        private static void Main()
        {
            // Testing different type of reverse algorithms
            Stopwatch timeTest = new Stopwatch();

            Console.Write("Enter some string: ");
            string str = Console.ReadLine();

            // Using StringBuilder
            timeTest.Start();
            string reversed = ReverseSB(str);
            timeTest.Stop();
            Console.WriteLine("Reverse text: {0}\ntime: {1} - StringBuilder class", reversed, timeTest.Elapsed);
            timeTest.Reset();

            Console.WriteLine();

            // Using Array.Reverse
            timeTest.Start();
            string reversedArrayReverse = ReverseArray(str);
            timeTest.Stop();
            Console.WriteLine("Reverse text: {0}\ntime: {1} - Array.Reverse", reversedArrayReverse, timeTest.Elapsed);
            timeTest.Reset();

            Console.WriteLine();

            // Using XOR
            timeTest.Start();
            string reversedXor = ReverseXor(str);
            timeTest.Stop();
            Console.WriteLine("Reverse text: {0}\ntime: {1} - XOR", reversedXor, timeTest.Elapsed);
            timeTest.Reset();
        }
        public void ShouldPerformFasterThanActivator()
        {
            // warmup
            for (var i = 0; i < 10; ++i)
            {
                Activator.CreateInstance<ClassWithDefaultConstuctor>();
                ReflectionHelpers.CreateInstance<ClassWithDefaultConstuctor>();
            }
            // warmup
            var count = 0;
            var stopWatch = new Stopwatch();

            stopWatch.Start();
            for (var i = 0; i < 1000000; ++i)
            {
                count += ReflectionHelpers.CreateInstance<ClassWithDefaultConstuctor>().Value;
            }
            stopWatch.Stop();
            var creatorTime = stopWatch.Elapsed;
            stopWatch.Reset();

            stopWatch.Start();
            for (var i = 0; i < 1000000; ++i)
            {
                count += Activator.CreateInstance<ClassWithDefaultConstuctor>().Value;
            }
            stopWatch.Stop();
            var activator = stopWatch.Elapsed;
            Assert.IsTrue(creatorTime < activator);
            Assert.AreEqual(2000000, count);
        }