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 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);
        }
        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();
        }
Example #4
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 #5
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);
        }
        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 #7
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 #8
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());
 }
        private void Upload()
        {
            DracoonClient.Log.Debug(LogTag, "Uploading file [" + FileUploadRequest.Name + "] in proxied way.");
            try {
                long   uploadedByteCount = 0;
                byte[] buffer            = new byte[DracoonClient.HttpConfig.ChunkSize];
                int    bytesRead         = 0;
                while ((bytesRead = InputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ProcessChunk(new Uri(UploadToken.UploadUrl), buffer, uploadedByteCount, bytesRead);
                    uploadedByteCount += bytesRead;
                }

                if (LastNotifiedProgressValue != uploadedByteCount)
                {
                    // Notify 100 percent progress
                    NotifyProgress(ActionId, uploadedByteCount, OptionalFileSize);
                }
            } catch (IOException ioe) {
                if (IsInterrupted)
                {
                    throw new ThreadInterruptedException();
                }

                const string message = "Read from stream failed!";
                DracoonClient.Log.Debug(LogTag, message);
                throw new DracoonFileIOException(message, ioe);
            } finally {
                ProgressReportTimer?.Stop();
            }
        }
Example #10
0
        public virtual void Update()
        {
            if (isStart == false)
            {
                return;
            }
            Currentframe++;

            stopwatch?.Restart();
            //Log.Trace("Update GOGOGOGOGO");


            _handlerComponent?.Update();
            stopwatch?.Stop();
            //if (stopwatch.ElapsedMilliseconds > 0)
            //    Log.Trace(Currentframe + "Update _handlerComponent 时间:" + stopwatch.ElapsedMilliseconds);


            stopwatch?.Restart();
            _envirinfoComponent?.Tick();
            stopwatch?.Stop();
            //if (stopwatch.ElapsedMilliseconds > 0)
            //    Log.Trace(Currentframe + "Update _envirinfoComponent 时间:" + stopwatch.ElapsedMilliseconds);

            stopwatch?.Restart();
            _taskEventComponent?.Update();
            stopwatch?.Stop();

            //if (stopwatch.ElapsedMilliseconds > 0)
            //    Log.Trace(Currentframe + "Update _taskEventComponent 时间:" + stopwatch.ElapsedMilliseconds);
        }
 /// <summary>
 /// Execute SP with return value as non Enumerable
 /// </summary>
 /// <param name="transit">return value as reference value</param>
 /// <param name="command">executive command</param>
 private void ExecuteWithSingleReturnValue(TransitObject transit, IDbCommand command)
 {
     command.Prepare();
     if (transit.ReturnType.IsClass && transit.ReturnType != typeof(string))
     {
         _queryTime?.Start();
         using (var reader = command.ExecuteReader())
         {
             _queryTime?.Stop();
             int columns  = reader.FieldCount;
             var accessor = TypeAccessor.Create(transit.ReturnType);
             foreach (var record in reader.ToRecord())
             {
                 var item = accessor.CreateNew();
                 ExtractObject(columns, item, accessor, record);
                 transit.ReturnObject = item;
                 break;
             }
         }
     }
     else
     {
         _queryTime?.Start();
         transit.ReturnObject = command.ExecuteScalar();
         _queryTime?.Stop();
     }
 }
Example #12
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 #13
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();
        }
Example #14
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());
            }
        }
Example #15
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 #16
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 #17
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;
        }
Example #18
0
        private static async Task ExecuteJobAsync(string id, IScheduledJob job, ILogger logger, bool tracingEnabled)
        {
            Stopwatch sw = tracingEnabled ? new Stopwatch() : null;

            try
            {
                sw?.Start();
                await job.ExecuteAsync();

                sw?.Stop();
                if (tracingEnabled)
                {
                    logger?.WriteInformation($"Job(Id: {id} , DisplayName: {job.DisplayName})已执行,耗时:{sw.ElapsedMilliseconds} 毫秒。");
                }
            }
            catch (Exception ex)
            {
                sw?.Stop();
                logger?.WriteError($"Job(Id: {id} , DisplayName: {job.DisplayName})执行作业时发生错误。", ex);
                ex.ThrowIfNecessary();
            }
            finally
            {
                IDisposable disposable = job as IDisposable;
                disposable?.Dispose();
            }
        }
        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 #20
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;
        }
    }
        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 #22
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);
 }
Example #23
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("");
        }
Example #24
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);
        }
        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 #26
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;
        }
        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);
        }
Example #28
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);
        }
Example #29
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);
        }
        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 #31
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);
            }
        }
        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 #33
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 #34
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 #35
0
 private static void Rec_OnRecordingComplete(object sender, RecordingCompleteEventArgs e)
 {
     Console.WriteLine("[+] Recording completed");
     _isRecording = false;
     _stopWatch?.Stop();
     Console.WriteLine(String.Format("File: {0}", e.FilePath));
     isDone = true;
 }
        private void OnPointerCancelled(object sender, PointerRoutedEventArgs e)
        {
            if (!_xfElement.IsVisible || FrameworkElement == null)
            {
                return;
            }
            PointerRoutedDebugMessage(e, "POINTER CANCELLED");

            long elapsed = 0;

            if (_holdTimer != null)
            {
                elapsed = _holdTimer.ElapsedMilliseconds;
                _holdTimer?.Stop();
                _holdTimer = null;
            }

            _releaseTimer?.Stop();
            _releaseTimer = null;

            foreach (var listener in _listeners)
            {
                if (listener.HandlesTapped)
                {
                    var args = new UwpTapEventArgs(FrameworkElement, e, _numberOfTaps)
                    {
                        Listener  = listener,
                        Cancelled = true
                    };
                    listener?.OnTapped(args);
                    e.Handled = args.Handled;
                }
                if (_longPressing && listener.HandlesLongPressed)
                {
                    var args = new UwpLongPressEventArgs(FrameworkElement, e, elapsed)
                    {
                        Listener  = listener,
                        Cancelled = true
                    };
                    listener?.OnLongPressed(args);
                    e.Handled = args.Handled;
                }
                if (listener.HandlesDown)
                {
                    var args = new UwpDownUpArgs(FrameworkElement, e)
                    {
                        Listener  = listener,
                        Cancelled = true
                    };
                    listener.OnUp(args);
                    e.Handled = args.Handled;
                    if (e.Handled)
                    {
                        return;
                    }
                }
            }
        }
        public async Task <TManagerCommandResponse> Handle <TManagerCommandRequest, TManagerCommandResponse>(TManagerCommandRequest request, CancellationToken cancellationToken)
            where TManagerCommandRequest : ManagerCommandRequest
            where TManagerCommandResponse : ManagerCommandResponse, new()
        {
            Guard.ArgumentNotNull(request, nameof(request));

            Stopwatch stopwatch = null;

            if (IsDebugEnabled || IsErrorEnabled)
            {
                stopwatch = Stopwatch.StartNew();
            }

            var commandHandler = _lifetimeScope.Resolve <IManagerCommandHandler <TManagerCommandRequest, TManagerCommandResponse> >();

            if (null == commandHandler)
            {
                Log.Warning("Cannot find handler for manager command for [<{request}, {response}>]",
                            typeof(TManagerCommandRequest).Name, typeof(TManagerCommandResponse).Name);

                return(ManagerCommandResponse.Create <TManagerCommandResponse>(
                           CommandExecutionStatus.ExecutionFailed,
                           new CommandExecutionInternalErrorResult(
                               $"Cannot find handler for manager command for [<{typeof(TManagerCommandRequest).Name}, {typeof(TManagerCommandResponse).Name}>]")));
            }

            Log.Debug("Starting processing manager command [<{request}, {response}>]",
                      typeof(TManagerCommandRequest).Name, typeof(TManagerCommandResponse).Name);

            try
            {
                var managerCommandResponse = await commandHandler.Handle(request, cancellationToken).ConfigureAwait(false);

                if (managerCommandResponse.CommandExecutionStatus == CommandExecutionStatus.Completed)
                {
                    stopwatch?.Stop();
                    Log.Debug("Finished processing manager command [<{request}, {response}>] {duration}",
                              typeof(TManagerCommandRequest).Name, typeof(TManagerCommandResponse).Name, stopwatch?.Elapsed);
                }
                else
                {
                    stopwatch?.Stop();
                    Log.Warning("Processing manager command [<{request}, {response}>] {duration} has failed with [{status}], [{message}]",
                                typeof(TManagerCommandRequest).Name, typeof(TManagerCommandResponse).Name, stopwatch?.Elapsed,
                                managerCommandResponse.CommandExecutionStatus, managerCommandResponse.CommandExecutionResult?.Description ?? "NULL");
                }

                return(managerCommandResponse);
            }
            catch (Exception ex)
            {
                stopwatch?.Stop();
                Log.Error(ex, "An error has occurred during processing manager command [<{request}, {response}>] [{duration}]",
                          typeof(TManagerCommandRequest).Name, typeof(TManagerCommandResponse).Name, stopwatch?.Elapsed);

                return(ManagerCommandResponse.Create <TManagerCommandResponse>(CommandExecutionStatus.InternalServerError, new CommandExecutionInternalErrorResult()));
            }
        }
Example #38
0
 private static void Rec_OnRecordingComplete(object sender, RecordingCompleteEventArgs e)
 {
     Console.WriteLine("Recording completed");
     _isRecording = false;
     _stopWatch?.Stop();
     Console.WriteLine(String.Format("File: {0}", e.FilePath));
     Console.WriteLine();
     Console.WriteLine("Press any key to exit");
 }
Example #39
0
        public void LogFailure(NpgsqlCommand command, Exception ex)
        {
            _stopwatch?.Stop();

            Console.WriteLine("Postgresql command failed!");
            Console.WriteLine(command.CommandText);
            foreach (var p in command.Parameters.OfType <NpgsqlParameter>())
            {
                Console.WriteLine($"  {p.ParameterName}: {p.Value}");
            }
            Console.WriteLine(ex);
        }
Example #40
0
        public void LogSuccess(NpgsqlCommand command)
        {
            _stopwatch?.Stop();

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                var message    = "Marten executed in {milliseconds} ms, SQL: {SQL}\n{PARAMS}";
                var parameters = command.Parameters.OfType <NpgsqlParameter>()
                                 .Select(p => $"  {p.ParameterName}: {p.Value}")
                                 .Join(Environment.NewLine);
                _logger.LogDebug(message, _stopwatch?.ElapsedMilliseconds ?? 0, command.CommandText, parameters);
            }
        }
        void OnManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
        {
            DebugMethodName(2);
            DebugMessage("Element=[" + _xfElement + "]");
            PointerDeviceTypeDebugMessage(e.PointerDeviceType);
            PositionDebugMessage(e.Position);
            ManipulationDeltaDebugMessage(e.Cumulative, "Cumul");
            ContainerDebugMessage(e.Container);
            HandledDebugString(e.Handled);

            if (!_xfElement.IsVisible || FrameworkElement == null)
            {
                return;
            }

            long elapsed = 0;

            if (_holdTimer != null)
            {
                elapsed = _holdTimer.ElapsedMilliseconds;
                _holdTimer?.Stop();
                _holdTimer = null;
            }
            DebugMessage("elapse=[" + elapsed + "]");
            if (!_panning || !_pinching || !_rotating)
            {
                _longPressing = elapsed > 750;
                if (_longPressing)
                {
                    foreach (var listener in _listeners)
                    {
                        if (listener.HandlesLongPressing)
                        {
                            var args = new UwpLongPressEventArgs(FrameworkElement, e, elapsed)
                            {
                                Listener = listener
                            };
                            listener?.OnLongPressing(args);
                            e.Handled = args.Handled;
                            DebugMessage("LongPressing Handled=[" + e.Handled + "]");
                            if (e.Handled)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            HandledDebugString(e.Handled);
        }
        public void LogSuccess(NpgsqlCommand command)
        {
            _stopwatch?.Stop();

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Marten executed in {milliseconds} ms, SQL: {SQL}", _stopwatch?.ElapsedMilliseconds ?? 0, command.CommandText);

                foreach (NpgsqlParameter p in command.Parameters)
                {
                    _logger.LogDebug("    {ParameterName}: {ParameterValue}", p.ParameterName, p.Value);
                }
            }
        }
Example #43
0
        public void Run()
        {
            try
            {
                _stopwatch = new Stopwatch();
                _stopwatch.Start();
                ProgressIcon    = FontAwesomeIcon.Refresh;
                ProgressSpin    = true;
                ProgressMessage = "Starting Server Timings trace...";
                ProgressColor   = "RoyalBlue";

                SetSelectedOutputTarget(OutputTarget.Timer);

                // clear out any existing benchmark tables
                BenchmarkDataSet.Tables.Clear();

                CreateSummaryOutputTable();
                CreateDetailOutputTable();

                // start server timings
                // once the server timings starts it will trigger the first query
                StartServerTimings();
            }
            catch (Exception ex)
            {
                Log.Error(ex, DaxStudio.Common.Constants.LogMessageTemplate, nameof(BenchmarkViewModel), nameof(Run), ex.Message);
                EventAggregator.PublishOnUIThread(new OutputMessage(MessageType.Error, $"An error occurred while attempting to run the benchmark: {ex.Message}"));
                _stopwatch?.Stop();
            }
        }
Example #44
0
        private static void OnOperationFinished()
        {
            _stopwatch?.Stop();

            switch (_operation)
            {
            case QueryProcessOperation.LinqParse:
                if (_options.LogLinqVisitorTime)
                {
                    PrintResult($"*** LINQ parsing time: {_stopwatch?.ElapsedMilliseconds} ms.");
                }
                return;

            case QueryProcessOperation.EsqGeneration:
                if (_options.LogQueryGenerationTime)
                {
                    PrintResult($"*** ESQ generation time: {_stopwatch?.ElapsedMilliseconds} ms.");
                }

                return;

            case QueryProcessOperation.Executing:
                if (_options.LogQueryExecutionTime)
                {
                    PrintResult($"*** Query execution time: {_stopwatch?.ElapsedMilliseconds} ms.");
                }

                return;
            }

            _stopwatch = null;
            LogWriter.EndScope();
        }
Example #45
0
        private PingReply SendCancellablePing(
            IPAddress targetAddress,
            int timeout,
            byte[] buffer,
            PingOptions pingOptions,
            Stopwatch?timer = null)
        {
            try
            {
                _sender = new Ping();

                timer?.Start();
                // 'SendPingAsync' always uses the default synchronization context (threadpool).
                // This is what we want to avoid the deadlock resulted by async work being scheduled back to the
                // pipeline thread due to a change of the current synchronization context of the pipeline thread.
                return(_sender.SendPingAsync(targetAddress, timeout, buffer, pingOptions).GetAwaiter().GetResult());
            }
            catch (PingException ex) when(ex.InnerException is TaskCanceledException)
            {
                // The only cancellation we have implemented is on pipeline stops via StopProcessing().
                throw new PipelineStoppedException();
            }
            finally
            {
                timer?.Stop();
                _sender?.Dispose();
                _sender = null;
            }
        }
        private async void CallGenerateCodes(Workspace workspace, string solutionFullName)
        {
            Stopwatch sw = null;

            try
            {
                sw = Stopwatch.StartNew();

                IProjectDtoControllersProvider controllersProvider = new DefaultProjectDtoControllersProvider();
                IProjectDtosProvider           dtosProvider        = new DefaultProjectDtosProvider(controllersProvider);

                DefaultTypeScriptClientProxyGenerator generator = new DefaultTypeScriptClientProxyGenerator(new DefaultBitCodeGeneratorOrderedProjectsProvider(),
                                                                                                            new BitSourceGeneratorBitConfigProvider(solutionFullName), dtosProvider
                                                                                                            , new DefaultTypeScriptClientProxyDtoGenerator(), new DefaultTypeScriptClientContextGenerator(), controllersProvider, new DefaultProjectEnumTypesProvider(controllersProvider, dtosProvider));

                await generator.GenerateCodes(workspace);

                Log($"Code Generation Completed in {sw.ElapsedMilliseconds} ms using {workspace.GetType().Name}");
            }
            catch (Exception ex)
            {
                LogException("Code Generation failed.", ex);
                throw;
            }
            finally
            {
                sw?.Stop();
            }
        }
Example #47
0
        static void UninstallHooks()
        {
            if (mouseHook != null)
            {
                mouseHook.MouseEvent -= MouseHook_MouseEvent;
                mouseHook.Uninstall();
                mouseHook = null;
            }

            if (keyboardHook != null)
            {
                keyboardHook.KeyEvent -= KeyboardHook_KeyEvent;
                keyboardHook.Uninstall();
                keyboardHook = null;
            }

            if (nanoHook != null)
            {
                nanoHook.Event -= NanoHook_Event;
                nanoHook.Uninstall();
                nanoHook = null;
            }

            afk_stopwatch?.Stop();
        }
Example #48
0
 public void Dispose()
 {
     stopwatch?.Stop();
     stopwatch = null;
     gameMemoryScanner?.Dispose();
     gameMemoryScanner = null;
 }
        private void Initialize()
        {
            SM = new StateMachine <States, Signals>();

            // Get the active state object to subscribe to OnStateEnter and OnStateLeave events.
            IState activeState = SM.CreateState(States.Active);

            // We want to only subscribe to OnStateEnter event of Stopped state. We can write an anonymous function such as:
            SM.CreateState(States.Stopped, States.Active).OnStateEnter += () => { stopwatch?.Stop(); Console.WriteLine("Elapsed time: " + stopwatch?.ElapsedMilliseconds.ToString()); };
            // We also only want to listen OnStateEnter event of Running state.
            SM.CreateState(States.Running, States.Active).OnStateEnter += () => { stopwatch?.Start(); };

            // Subscribe to activeState's event with anonymous functions.
            activeState.OnStateEnter += () => { stopwatch = stopwatch ?? new Stopwatch(); };
            activeState.OnStateLeave += () => { stopwatch?.Reset(); };

            // We do not need to get the signal objects if we don't want to. We can emit the signal with the Signals enum.
            SM.ConnectSignal(Signals.Reset, States.Active, States.Active, out ISignal resetSignal);
            SM.ConnectSignal(Signals.StartStop, States.Stopped, States.Running, out ISignal startStopSignal);
            SM.ConnectSignal(Signals.StartStop, States.Running, States.Stopped);

            SM.SetInitialState(States.Active);
            SM.SetInitialState(States.Stopped, States.Active);

            SM.OnStateChanged += SM_OnStateChanged;
        }
Example #50
0
        public new void Dispose()
        {
            Watcher?.Stop();
            Watcher = null;

            base.Dispose();
        }
Example #51
0
        void Update()
        {
            if (m_Store == null)
            {
                return;
            }

            m_Store.GetState().EditorDataModel.UpdateCounter++;
            m_Store.Update();

            IGraphModel currentGraphModel             = m_Store.GetState().CurrentGraphModel;
            Stencil     currentStencil                = currentGraphModel?.Stencil;
            bool        stencilRecompilationRequested = currentStencil && currentStencil.RecompilationRequested;

            if (stencilRecompilationRequested ||
                m_IdleTimer != null && Preferences.GetBool(VSPreferences.BoolPref.AutoRecompile) &&
                m_IdleTimer.ElapsedMilliseconds >= k_IdleTimeBeforeCompilationSeconds * 1000)
            {
                if (currentStencil && stencilRecompilationRequested)
                {
                    currentStencil.RecompilationRequested = false;
                }

                m_IdleTimer?.Stop();

                m_IdleTimer = null;
                OnCompilationRequest(RequestCompilationOptions.Default);
            }

            if (EditorApplication.isPlaying && !EditorApplication.isPaused)
            {
                m_Store.GetState().currentTracingFrame = Time.frameCount;
                m_Menu.UpdateUI();
            }
        }
Example #52
0
        private static void Rec_OnRecordingComplete(object sender, RecordingCompleteEventArgs e)
        {
            _stopWatch?.Stop();

            Console.Clear();
            ModifiedConsoleWrite(true,
                                 new string[] {
                "\nFile path: ", e.FilePath + '\n',
                "Length: ", _stopWatch.Elapsed.ToString() + '\n',
                "Press ", "[O]", " to open output directory\n",
                "      ", "[Enter]", " to start another recording\n",
                "      ", "[ESC]", " to Exit\n"
            },
                                 new ConsoleColor[] { ConsoleColor.Cyan, ConsoleColor.Cyan, ConsoleColor.Cyan, ConsoleColor.Cyan },
                                 new int[] { 1, 5, 8, 11 });
        }
Example #53
0
#pragma warning disable UseAsyncSuffix // Use Async suffix
        public async Task Invoke()
#pragma warning restore UseAsyncSuffix // Use Async suffix
        {
            Stopwatch stopwatch = null;

            try
            {
                stopwatch = Stopwatch.StartNew();

                await InvokeAsync();

                stopwatch.Stop();

                _logger.LogInformation(
                    $"Finished background task {JobName}. Execution time: {stopwatch.ElapsedMilliseconds}");
            }
            catch (Exception exception)
            {
                stopwatch?.Stop();

                _logger.LogError(
                    exception,
                    $"A task {JobName} has error: {exception.Message}");
            }
        }
Example #54
0
        private void CallGenerateCodes()
        {
            Stopwatch sw = null;

            try
            {
                sw = Stopwatch.StartNew();

                IProjectDtoControllersProvider controllersProvider = new DefaultProjectDtoControllersProvider();
                IProjectDtosProvider           dtosProvider        = new DefaultProjectDtosProvider(controllersProvider);

                DefaultHtmlClientProxyGenerator generator = new DefaultHtmlClientProxyGenerator(new DefaultBitCodeGeneratorOrderedProjectsProvider(),
                                                                                                new DefaultBitCodeGeneratorMappingsProvider(new DefaultBitConfigProvider()), dtosProvider
                                                                                                , new DefaultHtmlClientProxyDtoGenerator(), new DefaultHtmlClientContextGenerator(), controllersProvider, new DefaultProjectEnumTypesProvider(controllersProvider, dtosProvider));

                System.Threading.Tasks.Task.Run(async() => await generator.GenerateCodes(_visualStudioWorkspace, _shouldGeneratedProjectNames)).GetAwaiter().GetResult();

                Log($"Code Generation Completed in {sw.ElapsedMilliseconds} ms.");
            }
            catch (Exception ex)
            {
                LogException($"Code Generation failed.", ex);
            }
            finally
            {
                sw?.Stop();
            }
        }
Example #55
0
        public void Dispose()
        {
            if (disposed)
            {
                return;
            }

            lock (locker)
            {
                disposed = true;

                if (fileStream != null)
                {
                    bool deleteFile = fileStream.Length == 0;
                    fileStream.Flush();
                    fileStream.Close();
                    if (deleteFile)
                    {
                        File.Delete(FileName);
                    }
                }

                sw?.Stop();
            }
        }
Example #56
0
        private UTF.TestResult[] ExecuteTestWithDataRow(object dataRow, int rowIndex)
        {
            var       displayName = string.Format(CultureInfo.CurrentCulture, Resource.DataDrivenResultDisplayName, this.test.DisplayName, rowIndex);
            Stopwatch stopwatch   = null;

            UTF.TestResult[] testResults = null;
            try
            {
                stopwatch = Stopwatch.StartNew();
                this.testContext.SetDataRow(dataRow);
                testResults = this.ExecuteTest(this.testMethodInfo);
            }
            finally
            {
                stopwatch?.Stop();
                this.testContext.SetDataRow(null);
            }

            foreach (var testResult in testResults)
            {
                testResult.DisplayName  = displayName;
                testResult.DatarowIndex = rowIndex;
                testResult.Duration     = stopwatch.Elapsed;
            }

            return(testResults);
        }
        public static async Task Pause(this Stopwatch watch, int minDuration = 2500, int maxDuration = 5000)
        {
            watch?.Stop();
            await Task.Delay(Rng.Pseudo.GetInt32(minDuration, maxDuration));

            watch?.Start();
        }
 /// <summary>
 /// Stops the watch.
 /// </summary>
 protected void StopWatch()
 {
     stopwatch?.Stop();
     LastProcessingTime = stopwatch?.Elapsed ?? TimeSpan.Zero;
     stopwatch          = null;
     UpdateActivity(WorkerStatus.Idling);
 }
Example #59
0
        private void DoTask(CleanupWorkItem item)
        {
            Stopwatch sw = null;

            if (logger != null)
            {
                sw = Stopwatch.StartNew();
            }

            if (item.Task == CleanupWorkItem.Kind.RemoveFile)
            {
                RemoveFile(item);
            }
            else if (item.Task == CleanupWorkItem.Kind.CleanFolderRecursive || item.Task == CleanupWorkItem.Kind.CleanFolder)
            {
                CleanFolder(item, item.Task == CleanupWorkItem.Kind.PopulateFolderRecursive);
            }
            else if (item.Task == CleanupWorkItem.Kind.PopulateFolderRecursive || item.Task == CleanupWorkItem.Kind.PopulateFolder)
            {
                PopulateFolder(item, item.Task == CleanupWorkItem.Kind.PopulateFolderRecursive);
            }
            else if (item.Task == CleanupWorkItem.Kind.FlushAccessedDate)
            {
                FlushAccessedDate(item);
            }

            if (logger != null)
            {
                sw?.Stop();
            }
            logger?.LogTrace("{0}ms: Executing task {1} {2} ({3} tasks remaining)", sw?.ElapsedMilliseconds.ToString(NumberFormatInfo.InvariantInfo).PadLeft(4), item.Task.ToString(), item.RelativePath, queue.Count.ToString(NumberFormatInfo.InvariantInfo));
        }
        internal void Stop(ConnectionLossType cause)
        {
            if (stopping)
            {
                return;
            }
            else
            {
                stopping = true;
            }

            ConnectionToken?.Cancel();
            lastConnectionTestStopwatch?.Stop();
            pollingService?.Change(-1, -1);
            connectionStatusService?.Change(-1, -1);
            if (connection.ConnectionState == ConnectionState.Connected)
            {
                Send(Protocol.Connection_Close);
                Send(Protocol.Connection_Close);
            }

            connection.UnInitialize();
            ConnectionClosed?.Invoke(cause);
            connection.ConnectionState = ConnectionState.Offline;
        }