Пример #1
0
 public Task Load()
 {
     Stopwatch sw = new Stopwatch();
     sw.Start();
     StartLoading();
     Console.WriteLine("{1}. Start loading {0} ms.", sw.ElapsedMilliseconds, this.GetType().Name);
     sw.Restart();
     BeforeDataLoading();
     Console.WriteLine("{1}. Before data loading {0} ms.", sw.ElapsedMilliseconds, this.GetType().Name);
     sw.Restart();
     ClearData();
     Console.WriteLine("{1}. Clear data {0} ms.", sw.ElapsedMilliseconds, this.GetType().Name);
     sw.Restart();
     return Task.Factory.StartNew(() =>
         {
             dataSource = LoadDataFromServer();
             //Thread.Sleep(5000);
             Console.WriteLine("{1}. Load from server {0} ms.", sw.ElapsedMilliseconds, this.GetType().Name);
             sw.Restart();
         }).ContinueWith((task) =>
             {
                 Dispatcher.Invoke(new Action(() =>
                     {
                         AfterDataLoaded();
                         Console.WriteLine("{1}. After loading {0} ms.", sw.ElapsedMilliseconds, this.GetType().Name);
                         sw.Restart();
                         StopLoading();
                     }));
             }, TaskContinuationOptions.ExecuteSynchronously);
 }
Пример #2
0
        public static void Main()
        {
            Stopwatch timer = new Stopwatch();

            // Task 1
            databaseConnection = new TelerikAcademyEntities();
            using (databaseConnection)
            {
                timer.Restart();
                PrintEmployeesClean();
                Console.WriteLine("\nThe query for all employees WITHOUT include took: {0}.\nCheck screens in the solution folder for queries count!", timer.Elapsed);

                timer.Restart();
                PrintEmployeesIncluded();
                Console.WriteLine("\nThe query for all employees WITH include took: {0}.\nCheck screens in the solution folder for queries count!", timer.Elapsed);
            }

            // Task 2
            databaseConnection = new TelerikAcademyEntities();
            using (databaseConnection)
            {
                timer.Restart();
                GetEmployeesFromSofiaUnoptimized();
                Console.WriteLine("\nTo list operations took: {0} with N queries.", timer.Elapsed);

                timer.Restart();
                GetEmployeesFromSofiaOptimizedOne();
                Console.WriteLine("\nOptimized #1 query took: {0} with 1 querie.", timer.Elapsed);

                timer.Restart();
                GetEmployeesFromSofiaOptimizedTwo();
                Console.WriteLine("\nOptimized #2 query took: {0} with 1 querie.", timer.Elapsed);
            }
        }
Пример #3
0
        private static void runTestFile(string filename)
        {
            string staCode = "";

            using (var staFile = new FileStream("sta.js", FileMode.Open, FileAccess.Read))
                staCode = new StreamReader(staFile).ReadToEnd();
            Console.WriteLine("Start processing file: " + filename);
            var f  = new FileStream(filename, FileMode.Open, FileAccess.Read);
            var sr = new StreamReader(f);
            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            var s = new Module(staCode);

            sw.Stop();
            Console.WriteLine("Sta compile time: " + sw.Elapsed);
            sw.Restart();
            s.Run();
            sw.Stop();
            Console.WriteLine("Sta init time: " + sw.Elapsed);
            Console.WriteLine("Start evaluation of the file");
            Console.WriteLine("-------------------------------------");
            sw.Restart();
            s.Context.Eval(sr.ReadToEnd(), true);
            sw.Stop();
            Console.WriteLine("-------------------------------------");
            Console.WriteLine("Complite within " + sw.Elapsed);
            sr.Dispose();
            f.Dispose();
        }
Пример #4
0
        static void ExpressionHashTiming() {
            var timer = new Stopwatch();

            Console.WriteLine("Generating dynamically specialized code...");
            timer.Start();
            var specializedExpression = ExpressionHashUtil.Example.Specialize();
            var specializedMethod = specializedExpression.Compile();
            Console.WriteLine("Done after {0:0}ms", timer.Elapsed.TotalMilliseconds);

            // -- uncomment to output the IL to disk, where it can be inspected more easily
            //ExpressionHashUtil.WriteMethodToAssembly(specializedExpression, "Example");
            
            Console.WriteLine("Timing interpretation vs dynamically generated code of example hash...");
            var repeatCount = 10;
            var streamSize = 1 << 24;
            foreach (var _ in Enumerable.Range(0, repeatCount)) {
                timer.Restart();
                var r1 = ExpressionHashUtil.Example.Interpret(new CountingStream(streamSize));
                var t1 = timer.Elapsed;
                Console.Write("Interpreted: {0:0}ms", t1.TotalMilliseconds);
                
                timer.Restart();
                var r2 = specializedMethod(new CountingStream(streamSize));
                var t2 = timer.Elapsed;
                Console.Write(", Specialized: {0:0}ms", t2.TotalMilliseconds);
                Console.WriteLine(r1 == r2 ? "" : ", !!!Didn't match!!!");
            }
        }
Пример #5
0
        public void CompareStringReplaceMethods()
        {
            const int times = 1000;

            var watch = new Stopwatch();

            watch.Restart();
            for (var i = 0; i < times; i++)
            {
                var resultsA = StringReplaceMethodA(CONTENT_A);
            }
            watch.Stop();

            Console.WriteLine("Time taken for Method A : " + watch.ElapsedMilliseconds + "ms");

            watch.Restart();
            for (var i = 0; i < times; i++)
            {
                var resultsB = StringReplaceMethodB(CONTENT_A);
            }
            watch.Stop();

            Console.WriteLine("Time taken for Method B : " + watch.ElapsedMilliseconds + "ms");

            watch.Restart();
            for (var i = 0; i < times; i++)
            {
                var resultsB = StringReplaceMethodC(CONTENT_A);
            }
            watch.Stop();

            Console.WriteLine("Time taken for Method C : " + watch.ElapsedMilliseconds + "ms");

            Assert.IsNotNull("hello");
        }
Пример #6
0
        private void Test()
        {
            System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();

            Random r = new Random();

            int[] array10k = Enumerable.Repeat(0, 10000).Select(i => r.Next()).ToArray();

            SortAlgorithm.Heapsort <int>(array10k, (p1, p2) => p1.CompareTo(p2));

            watch.Stop();
            Debug.WriteLine($"Heapsort, {array10k.Length}, {watch.ElapsedMilliseconds / 1000.0}");
            watch.Restart();

            SortAlgorithm.MergeSort <int>(array10k, (p1, p2) => p1.CompareTo(p2));

            watch.Stop();
            Debug.WriteLine($"MergeSort, {array10k.Length}, {watch.ElapsedMilliseconds / 1000.0}");
            watch.Restart();

            SortAlgorithm.QuickSort <int>(array10k, (p1, p2) => p1.CompareTo(p2));

            watch.Stop();
            Debug.WriteLine($"QuickSort, {array10k.Length}, {watch.ElapsedMilliseconds / 1000.0}");
            watch.Restart();

            SortAlgorithm.BubbleSort <int>(array10k, (p1, p2) => p1.CompareTo(p2));

            watch.Stop();
            Debug.WriteLine($"BubbleSort, {array10k.Length}, {watch.ElapsedMilliseconds / 1000.0}");
            watch.Restart();
        }
Пример #7
0
        private static void TestGetPalindromes(string text)
        {
            var sw = new Stopwatch();
            SimpleImplementation.count = 0;
            sw.Restart();
            var expected = SimpleImplementation.GetPalindromes(text).ToArray();
            sw.Stop();
            var simpleCount = SimpleImplementation.count;
            var simpleTime = sw.Elapsed;

            Implementation1.count = 0;
            sw.Restart();
            var actual = Implementation1.GetPalindromes(text).ToArray();
            sw.Stop();
            var newCount = Implementation1.count;
            var newTime = sw.Elapsed;

            Console.WriteLine("べた実装 {0}, {2}. 新実装 {1}, {3}", simpleCount, newCount, simpleTime, newTime);

            if (!expected.OrderBy(x => x).SequenceEqual(actual.OrderBy(x => x)))
            {
                Console.WriteLine("error GetPalindromes");

                Console.WriteLine(string.Join(", ", expected));
                Console.WriteLine(string.Join(", ", actual));
            }
        }
Пример #8
0
 static void Main(string[] args)
 {
     Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
     var useCaseTypes =
         typeof(Program).Assembly.GetTypes().Where(t => typeof(UseCase).IsAssignableFrom(t) && t != typeof(UseCase)).ToArray();
     useCaseTypes = useCaseTypes.Concat(useCaseTypes).ToArray();
     foreach (var useCaseType in useCaseTypes.OrderByDescending(t=>t.Name))
     {
         var sw = new Stopwatch();
         GC.Collect(GC.MaxGeneration);
         GC.WaitForPendingFinalizers();
         GC.Collect(GC.MaxGeneration);
         Logger.InstanceCount = 0;
         ErrorHandler.InstanceCount = 0;
         sw.Start();
         var uc = (UseCase)useCaseType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
         uc.Run();
         sw.Stop();
         var initTicks = sw.Elapsed.TotalMilliseconds;
         sw.Restart();
         for (int i = 0; i < 100000; i++) uc.AddToCheck(uc.Run());
         sw.Stop();
         var runTicks = sw.Elapsed.TotalMilliseconds;
         uc.Check();
         sw.Restart();
         uc = (UseCase) useCaseType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
         uc.Run();
         sw.Stop();
         var init2Ticks = sw.Elapsed.TotalMilliseconds;
         Console.WriteLine("{0,-20} {1,8:N1}ms init:{2,7:N2}ms 2nd init:{3,7:N2}ms ch: {4} {5}", useCaseType.Name, runTicks, initTicks, init2Ticks, Logger.InstanceCount, ErrorHandler.InstanceCount);
     }
 }
Пример #9
0
		public static void Run()
		{
			Parse ();

			var pcw = new LegacyParseCacheView (new[]{ srcDir });
			var ctxt = new ResolutionContext (pcw, new ConditionalCompilationFlags(versions,0, true));

			var mod = pcw.LookupModuleName (null, "botan.pubkey.algo.dsa").First();
			var scope = ResolutionTests.N<DMethod> (mod, "DSAVerificationOperation.verify");
			var scopedStmt = ResolutionTests.S (scope, 9);

			ctxt.Push (scope, scopedStmt.Location);

			ITypeDeclaration td = new IdentifierDeclaration ("q"){ Location = scopedStmt.Location };
			AbstractType t;

			var sw = new Stopwatch ();
			Console.WriteLine ("Begin resolving...");
			sw.Restart ();
			t = TypeDeclarationResolver.ResolveSingle(td, ctxt);

			sw.Stop ();

			Console.WriteLine ("Finished resolution. {0} ms.", sw.ElapsedMilliseconds);

			sw.Restart ();
			t = TypeDeclarationResolver.ResolveSingle(td, ctxt);

			sw.Stop ();

			Console.WriteLine ("Finished resolution. {0} ms.", sw.ElapsedMilliseconds);
		}
Пример #10
0
        static void Main(string[] args)
        {
            dynamic x = new Speaker();
            x.Clonk();

            return;

            var expression = "import pythonDemo\npythonDemo.factorial(2000)";
            var engine = Python.CreateEngine();

            Stopwatch sw = new Stopwatch();

            int max = 10;

            sw.Start();
            for (int i = 0; i < max; ++i) engine.Execute(expression);
            sw.Stop();
            Console.WriteLine("Python={0}", sw.Elapsed);
            sw.Restart();
            for (int i = 0; i < max; ++i) factDyn(2000);
            sw.Stop();
            Console.WriteLine("Dynamic={0}", sw.Elapsed);
            sw.Restart();
            for (int i = 0; i < max; ++i) fact(2000);
            sw.Stop();
            Console.WriteLine("Typed={0}", sw.Elapsed);

            Console.Beep(1000, 2000);

            //Console.WriteLine(result);
            Console.ReadKey();
        }
Пример #11
0
        static void Main(string[] args) {
            const int terminoFibonacci = 40;
            int resultado;

            var crono = new Stopwatch();
            crono.Start();
            resultado = FibonacciNoMemorizado.Fibonacci(terminoFibonacci);
            crono.Stop();
            long ticksNoMemorizadoPrimeraLlamada = crono.ElapsedTicks;
            Console.WriteLine("Versión no memorizada, primera llamada: {0:N} ticks. Resultado: {1}.", ticksNoMemorizadoPrimeraLlamada, resultado);

            crono.Restart();
            resultado = FibonacciNoMemorizado.Fibonacci(terminoFibonacci);
            crono.Stop();
            long ticksNoMemorizadoSegundaLlamada = crono.ElapsedTicks;
            Console.WriteLine("Versión no memorizada, segunda llamada: {0:N} ticks. Resultado: {1}.", ticksNoMemorizadoSegundaLlamada, resultado);

            crono.Restart();
            resultado = FibonacciMemorizacion.Fibonacci(terminoFibonacci);
            crono.Stop();
            long ticksMemorizadoPrimeraLlamada = crono.ElapsedTicks;
            Console.WriteLine("Versión memorizada, primera llamada: {0:N} ticks. Resultado: {1}.", ticksMemorizadoPrimeraLlamada, resultado);

            crono.Restart();
            resultado = FibonacciMemorizacion.Fibonacci(terminoFibonacci);
            crono.Stop();
            long ticksMemorizadoSegundaLlamada = crono.ElapsedTicks;
            Console.WriteLine("Versión memorizada, segunda llamada: {0:N} ticks. Resultado: {1}.", ticksMemorizadoSegundaLlamada, resultado);
        }
Пример #12
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);
        }
Пример #13
0
 protected void signal_decode(SignalKey sigKey)
 {
     if (sigKey.Signal != null)
     {
         redRat3.RCDetectorEnabled = false;
         bool key_exist = all_button_name.Contains(sigKey.Signal.Name);
         if (key_exist)
         {
             BeginInvoke((MethodInvoker) delegate
             {
                 if (richTextBoxScript.Lines.Length < 1 || !sw.IsRunning)
                 {
                     sw.Restart();
                     richTextBoxScript.Text += ("redrat " + sigKey.Signal.Name + " ");
                 }
                 else
                 {
                     richTextBoxScript.Text += (Convert.ToInt32(sw.Elapsed.TotalMilliseconds) + "\n" + "redrat " + sigKey.Signal.Name + " ");
                 }
                 sw.Restart();
                 richTextBoxScript.SelectionStart = richTextBoxScript.TextLength;
                 // Scrolls the contents of the control to the current caret position.
                 richTextBoxScript.ScrollToCaret();
             });
             decision_sound.Play();
             signal_receive_Delay(150); //防止接收重複信號
             redRat3.ClearRCSignalInQueue();
             redRat3.RCDetectorEnabled = true;
         }
     }
 }
        public static void Main()
        {
            var data = new ProductsData();

            for (int i = 0; i < 10000; i++)
            {
                int id = i;
                string title = "title" + i % 10;
                string supplier = "supplier" + i % 10;
                decimal price = i + 0.25m;
                data.Add(id, title,supplier,price);
            }

            var sw = new Stopwatch();

            sw.Start();
            var productsInRange = data.FindProductsInPriceRange(10, 20);
            Console.WriteLine(string.Join(Environment.NewLine, productsInRange));
            Console.WriteLine(sw.Elapsed);

            sw.Restart();
            Console.WriteLine(new string('*', 20));
            var productsByTitleInRange = data.FindProductsByTitleAndPriceRange("title1", 1, 100);
            Console.WriteLine(string.Join(Environment.NewLine, productsByTitleInRange));
            Console.WriteLine(sw.Elapsed);

            sw.Restart();
            Console.WriteLine(new string('*', 20));
            var productsBySupplierInRange = data.FindProductsBySupplierAndPriceRange("supplier2", 35, 66);
            Console.WriteLine(string.Join(Environment.NewLine, productsBySupplierInRange));
            Console.WriteLine(sw.Elapsed);
        }
Пример #15
0
        private static void Main(string[] args)
        {
            Settings.Init();
            client = new GameClient();

            MRandom = new Random();

            window.Closed += WindowOnClosed;
            window.MouseMoved += WindowOnMouseMoved;
            window.MouseButtonPressed += WindowOnMouseButtonPressed;
            window.KeyPressed += WindowOnKeyPressed;
            window.KeyReleased += WindowOnKeyReleased;
            window.MouseButtonReleased += WindowOnMouseButtonReleased;
            window.SetFramerateLimit(75);
            client.GameMode = new StandardMelee(client.InputHandler);

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

            manager.SwitchState(new MainMenuState(), null);

            while (window.IsOpen())
            {
                window.DispatchEvents();
                window.Clear(new Color(100, 100, 200));

                var dt = (float) (stopwatch.Elapsed.TotalSeconds*1000);
                stopwatch.Restart();

                manager.Update(dt);
                manager.Render(window);
                window.Display();
            }
        }
Пример #16
0
        public void should_be_within_performace_tolerance()
        {
            var json = File.ReadAllText("model.json");
            var jsonBytes = new MemoryStream(File.ReadAllBytes("model.json"));
            var stopwatch = new Stopwatch();

            var controlBenchmark = Enumerable.Range(1, 1000).Select(x =>
            {
                jsonBytes.Seek(0, SeekOrigin.Begin);
                stopwatch.Restart();
                json.ParseJson();
                stopwatch.Stop();
                return stopwatch.ElapsedTicks;
            }).Skip(5).Average();

            var flexoBenchmark = Enumerable.Range(1, 1000).Select(x =>
            {
                jsonBytes.Seek(0, SeekOrigin.Begin);
                stopwatch.Restart();
                JElement.Load(jsonBytes);
                stopwatch.Stop();
                return stopwatch.ElapsedTicks;
            }).Skip(5).Average();

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

            flexoBenchmark.ShouldBeLessThan(controlBenchmark * 2);
        }
Пример #17
0
      private static void BenchmarkFingerprintComparer()
      {
         var sw = new Stopwatch();
         var fingerprint1 = new int[1981];
         var fingerprint2 = new int[2016];

         for (int j = 0; j < 5; j++)
         {
            sw.Restart();
            for (int i = 0; i < 100; i++)
            {
               FingerprintComparer.MatchFingerprints3(fingerprint1, fingerprint2, -1);
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);

            sw.Restart();
            for (int i = 0; i < 100; i++)
            {
               ChromaprintFingerprinter.MatchFingerprints(fingerprint1, fingerprint2, -1);
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);

            Console.WriteLine();
         }
      }
Пример #18
0
        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);
        }
        public async Task<Dictionary<string, string>> Get([FromUri] long cycles)
        {
            //Sanitize
            cycles = cycles > 1000000000 ? 1 : cycles;

            var computations = new Computations();

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

            stopwatch.Restart();
            computations.DoWork(cycles);
            var inOrderSpan = stopwatch.Elapsed;

            stopwatch.Restart();
            await computations.DoWorkAsync(cycles);
            var asyncSpan = stopwatch.Elapsed;

            var returnDictionary = new Dictionary<string, string>
            {
                {"processors", Environment.ProcessorCount.ToString()},
                {"inOrderSpan", inOrderSpan.ToString()},
                {"asyncSpan", asyncSpan.ToString()}
            };

            var results = JsonConvert.SerializeObject(returnDictionary);
            LogManager.GetCurrentClassLogger().Log(LogLevel.Info, results);

            return returnDictionary;
        }
        static void Main(string[] args)
        {
            Console.Title = "利用PLinq实现集合的并行化查询";

            Stopwatch watch = new Stopwatch();          //初始化时间测量器
            var dataset = Enumerable.Range(1, 100);   //生成1到100的整数序列
            watch.Start();                              //开始测量时间
            var res1 = dataset.Where(i => i % 3 == 0);  //串行查询能整除3的整数
            Console.WriteLine("利用Where方法串行查询耗时:{0}微秒\n", watch.ElapsedTicks / 10);
            watch.Restart();                            //重置时间测量器
            //并行查询能整除3的整数
            var res2 = dataset.AsParallel().Where(i => i % 3 == 0);//并行查询能整除3的整数
            Console.WriteLine("利用Where方法并行查询能整除3的整数耗时:{0}微秒\n", watch.ElapsedTicks / 10);
            watch.Restart();                            //重置时间测量器
            //并行查询能整除3的整数,并对结果进行排序
            var res3 = dataset.AsParallel().AsOrdered().Where(i => i % 3 == 0);
            Console.WriteLine("利用Where方法并行查询能整除3的整数,并对结果进行排序耗时:{0}微秒\n", watch.ElapsedTicks / 10);
            watch.Restart();                            //重置时间测量器
            //利用LINQ语句并行查询能整除3的整数,并对结果进行排序
            var res4 = from i in dataset.AsParallel().AsOrdered() where i % 3 == 0 select i;
            Console.WriteLine("利用LINQ语句并行查询能整除3的整数,并对结果进行排序耗时:{0}微秒\n", watch.ElapsedTicks / 10);
            watch.Restart();                            //重置时间测量器
            //串行输出查询结果
            foreach (var item in res4) { Thread.Sleep(1); Console.Write("{0,3}", item); }
            Console.WriteLine("\n串行输出查询结果:{0:N}微秒", watch.ElapsedTicks / 10);
            watch.Restart();                            //重置时间测量器
            //并行输出查询结果
            res2.ForAll((item) => { Thread.Sleep(1); Console.Write("{0,3}", item); });
            Console.WriteLine("\n并行输出查询结果:{0:N}微秒", watch.ElapsedTicks / 10);

            Console.ReadLine();
        }
Пример #21
0
        static void Main(string[] args)
        {
            var sourceList = new Item[10000];
            for (int i = 0; i < sourceList.Length; i++)
            {
                sourceList[i] = new Item { IntValue = i, StringValue = i.ToString() };
            }
            var mySerializer = new YamlSerializer();
            var myDeserializer = new YamlDeserializer();
            var defaultSerializer = new Serializer();
            var defaultDeserializer = new Deserializer();
            var watch = new Stopwatch();

            while (true)
            {
                var sw = new StringWriter();
                watch.Restart();
                mySerializer.Serialize(sw, sourceList);
                var stime = watch.ElapsedMilliseconds;
                watch.Restart();
                var list = myDeserializer.Deserialize<List<Item>>(new StringReader(sw.ToString()));
                var dtime = watch.ElapsedMilliseconds;
                Console.WriteLine("My - Serialize time: {0}ms, Deserialize time: {1}ms", stime, dtime);

                sw = new StringWriter();
                watch.Restart();
                defaultSerializer.Serialize(sw, sourceList);
                stime = watch.ElapsedMilliseconds;
                watch.Restart();
                list = defaultDeserializer.Deserialize<List<Item>>(new StringReader(sw.ToString()));
                dtime = watch.ElapsedMilliseconds;
                Console.WriteLine("Default - Serialize time: {0}ms, Deserialize time: {1}ms", stime, dtime);
            }
        }
Пример #22
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);
        }
Пример #23
0
        /// <summary>
        /// Checks if there were any changes in document types defined in Umbraco/uSiteBuilder/Both.
        /// Does not check relations between document types (allowed childs and allowable parents)
        /// </summary>
        /// <param name="hasDefaultValues"></param>
        /// <returns></returns>
        public static List<ContentComparison> PreviewDocumentTypeChanges(out bool hasDefaultValues)
        {
            #if DEBUG
            Stopwatch timer = new Stopwatch();
            timer.Start();
            #endif
            // compare the library based definitions to the Umbraco DB
            var definedDocTypes = PreviewDocTypes(typeof(DocumentTypeBase), "");

            #if DEBUG
            timer.Stop();
            StopwatchLogger.AddToLog(string.Format("Total elapsed time for method 'DocumentTypeComparer.PreviewDocumentTypeChanges' - only PreviewDocTypes: {0}ms.", timer.ElapsedMilliseconds));
            timer.Restart();
            #endif

            #if DEBUG
            timer.Start();
            #endif
            hasDefaultValues = _hasDefaultValues;
            // add any umbraco defined doc types that don't exist in the class definitions
            definedDocTypes.AddRange(ContentTypeService.GetAllContentTypes()
                                         .Where(doctype => definedDocTypes.All(dd => dd.Alias != doctype.Alias))
                                         .Select(docType => new ContentComparison { Alias = docType.Alias, DocumentTypeStatus = Status.Deleted, DocumentTypeId = docType.Id }));

            #if DEBUG
            timer.Stop();
            StopwatchLogger.AddToLog(string.Format("Total elapsed time for method 'DocumentTypeComparer.PreviewDocumentTypeChanges' - add any umbraco defined doc types that don't exist in the class definitions: {0}ms.", timer.ElapsedMilliseconds));
            timer.Restart();
            #endif

            return definedDocTypes;
        }
Пример #24
0
        public static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            int[] arr = Util.readInts("1Kints.txt");
            Console.WriteLine(count(arr) + " triplete cu suma 0");
            sw.Stop();
            Console.WriteLine(sw.Elapsed);

            sw.Restart();
            arr = Util.readInts("2Kints.txt");
            Console.WriteLine(count(arr) + " triplete cu suma 0");
            sw.Stop();
            Console.WriteLine(sw.Elapsed);

            sw.Restart();
            arr = Util.readInts("4Kints.txt");
            Console.WriteLine(countFast(arr) + " triplete cu suma 0");
            sw.Stop();
            Console.WriteLine(sw.Elapsed);

            sw.Restart();
            arr = Util.readInts("8Kints.txt");
            Console.WriteLine(countFast(arr) + " triplete cu suma 0");
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
        }
        public async Task<Dictionary<string, string>> Get([FromUri] int ms)
        {
            //Sanitize
            ms = ms > 2000 ? 1 : ms;

            var waiting = new Waiter();

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

            stopwatch.Restart();
            waiting.DoWork(ms);
            var inOrderSpan = stopwatch.Elapsed;

            stopwatch.Restart();
            await waiting.DoWorkAsync(ms);
            var asyncSpan = stopwatch.Elapsed;

            var returnDictionary = new Dictionary<string, string>
            {
                {"processors", Environment.ProcessorCount.ToString()},
                {"inOrderSpan", inOrderSpan.ToString()},
                {"asyncSpan", asyncSpan.ToString()}
            };

            var results = JsonConvert.SerializeObject(returnDictionary);
            LogManager.GetCurrentClassLogger().Log(LogLevel.Info, results);

            return returnDictionary;
        }
Пример #26
0
        public Language Read()
        {
            var sw = new Stopwatch();
            sw.Start();

            _orthography = ReadOrthography();
            Debug.Print("orthograpy: " + sw.ElapsedMilliseconds.ToString() + " ms");
            sw.Restart();

            Morphotactics morphotactics = ReadMorphotactics();
            Debug.Print("morphotactics: " + sw.ElapsedMilliseconds.ToString() + " ms");
            sw.Restart();

            MorphemeSurfaceDictionary<Root> roots = ReadRoots();
            Debug.Print("roots: " + sw.ElapsedMilliseconds.ToString() + " ms");
            sw.Restart();

            Suffixes suffixes = ReadSuffixes();
            Debug.Print("suffixes: " + sw.ElapsedMilliseconds.ToString() + " ms");
            sw.Restart();

            int index = _dirPath.LastIndexOf("\\");

            string langCode = index > -1 ? _dirPath.Substring(index + 1) : _dirPath;

            return new Language(langCode, morphotactics, roots, suffixes);
        }
        static void Main(string[] args)
        {
            var context = new SoftUniEntities();

            var totalCount = context.Employees.Count();

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

            PrintNamesWithNativeQuery();
            Console.WriteLine("\nNative: {0}\n\n", sw.Elapsed);

            sw.Restart();

            PrintNamesWithLinqQuery_LINQtoEntities();

            Console.WriteLine("\n\nLINQtoEntities: {0}\n\n", sw.Elapsed);

            sw.Restart();

            PrintNamesWithLinqQuery_WithExtensionMethods();

            Console.WriteLine("\n\nLINQWithExtensionMethods: {0}", sw.Elapsed);

            sw.Stop();
        }
Пример #28
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);
 }
Пример #29
0
        static void Main(string[] args)
        {
            var context = new AdsEntities();

            context.Database.ExecuteSqlCommand("CHECKPOINT; DBCC DROPCLEANBUFFERS;");

            var nonOptimizedRunningTimes = new List<TimeSpan>();
            var optimizedRunningTimes = new List<TimeSpan>();
            var sw = new Stopwatch();
            
            sw.Start();

            for (int i = 0; i < 10; i++)
            {
                NonOptimizedQuery(context);
                nonOptimizedRunningTimes.Add(sw.Elapsed);
                sw.Restart();
            }

            for (int i = 0; i < 10; i++)
            {
                OptimizedQuery(context);
                optimizedRunningTimes.Add(sw.Elapsed);
                sw.Restart();
            }

            Console.WriteLine("NonOptimized: {0}", nonOptimizedRunningTimes.Average(ts => ts.TotalMilliseconds));
            Console.WriteLine("Optimized: {0}", optimizedRunningTimes.Average(ts => ts.TotalMilliseconds));
        }
Пример #30
0
        static void Main( string[] args )
        {
            Stopwatch sw = new Stopwatch();

            int count = 1000000;

            var buffer = new double[count];

            sw.Restart();
            for ( int i = 0; i < count; i++ ) {
                buffer[i] = Math.Sqrt( (double)i );
            }

            var MathSqrt = sw.ElapsedMilliseconds;

            sw.Restart();
            for ( int i = 0; i < count; i++ ) {
                buffer[i] = t_sqrtF( (float)i );
            }

            var FastSqrtF = sw.ElapsedMilliseconds;

            sw.Restart();
            for ( int i = 0; i < count; i++ ) {
                buffer[i] = t_sqrtD( (double)i );
            }

            var FastSqrtD = sw.ElapsedMilliseconds;

            Console.WriteLine("");
            Console.WriteLine( "MathSqrt  : " + MathSqrt );
            Console.WriteLine( "FastSqrtF : " + FastSqrtF );
            Console.WriteLine( "FastSqrtD : " + FastSqrtD );
        }
Пример #31
0
        static void Main(string[] args)
        {
            Console.WriteLine("Started publisher and inserting data.");
            Publisher.Start();
    
            var config = new Configuration();
            config.Configure("nh.sqlserver.config");
            config.SessionFactoryName("Test session factory");
            config.AddAssembly(typeof(Dog).Assembly);

            new SchemaUpdate(config).Execute(false, true);
            
            using(var sessionFactory = config.BuildSessionFactory())
            {
                Stopwatch sw = new Stopwatch();

                sw.Start();
                InsertData(sessionFactory);
                Console.WriteLine("Inserting data  with logging took: {0}", sw.Elapsed);

                sw.Restart();
                Publisher.Shutdown();
                Console.WriteLine("Publisher shutdown complete in {0}", sw.Elapsed);

                Console.WriteLine("inserting data with publisher shutdown");
                sw.Restart();
                InsertData(sessionFactory);
                Console.WriteLine("Inserting data  without logging took: {0}", sw.Elapsed);
            }
            Console.ReadLine();
        }
Пример #32
0
        public static void RunExamples()
        {
            List<SpreadSheetExample> examples = BuildExamples();
            var runner = new SpreadSheetExampleRunner();

            var csvText = new StringBuilder();

            var watch = new Stopwatch();
            watch.Restart();
            System.Threading.Thread.Sleep(10);

            foreach (SpreadSheetExample example in examples)
            {
                watch.Restart();
                var results = runner.Run(example);
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;

                runner.PrintResults(results, example, elapsedMs, csvText);
            }


            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            File.WriteAllText(path + @"\Result.csv", csvText.ToString());
        }
Пример #33
0
        static void Main(string[] args)
        {
            long ms = 0;
            Stopwatch timer = new Stopwatch();
            timer.Start();

            Console.WriteLine("Reading");
            var image = new ImageBinarizer("..\\..\\..\\test4.jpg");
            PrintTime(timer);
            ms += timer.ElapsedMilliseconds;
            timer.Restart();

            Console.WriteLine("Binarization");
            image.StartThresholding();
            PrintTime(timer);
            ms += timer.ElapsedMilliseconds;
            timer.Restart();

            Console.WriteLine("Writing");
            image.SaveTo("..\\..\\..\\out.bmp");

            timer.Stop();
            ms += timer.ElapsedMilliseconds;
            PrintTime(timer);

            Console.WriteLine("Full time: " + ms);
            Thread.Sleep(3000);
            //Console.ReadKey();
        }
Пример #34
0
        public static void Main2(string[] args)
        {
            Random rnd = Random;

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            Console.WriteLine("Start RDF-Store Main2()");
            string mag_path = "mag_data/";
            string mag_data = mag_path + "mag_data.ttl";
            bool   toload   = false;

            if (!Directory.Exists(mag_path))
            {
                toload = true; Directory.CreateDirectory(mag_path);
            }
            FileStream fs = File.Open(mag_data, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            TextWriter tw = new StreamWriter(fs);

            _dataDirectory = mag_path;
            Store stor      = new Store(mag_path);
            int   nelements = 1_000_000;

            if (toload)
            {
                sw.Restart();
                tw.WriteLine("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .");
                tw.WriteLine("@prefix iis: <http://www.iis.nsk.su/> .");

                for (int i = 0; i < nelements; i++)
                {
                    tw.WriteLine($"<p{i}> ");
                    tw.WriteLine($"\trdf:type <person>;");
                    tw.WriteLine($"\tiis:name \"pupkin{i}\";");
                    tw.WriteLine($"\t<age> \"{(double)(rnd.NextDouble() * 100)}\".");
                }
                tw.Flush();
                fs.Close();
                sw.Stop();
                Console.WriteLine($"data {nelements} build ok. duration={sw.ElapsedMilliseconds}");

                sw.Restart();
                //var stor = new Store(mag_path);
                stor.ReloadFrom(mag_data);
                stor.BuildIndexes();
                sw.Stop();
                Console.WriteLine($"data {nelements} load ok. duration={sw.ElapsedMilliseconds}");
            }
            int nprobe = 100;

            sw.Restart();
            for (int j = 0; j < nprobe; j++)
            {
                string squery = "select * { <p" + rnd.Next(nelements) + "> ?p ?o }";
                var    r1     = stor.ParseRunSparql(squery).ToCommaSeparatedValues();
                //Console.WriteLine(r1);
            }
            sw.Stop();
            Console.WriteLine($"{nprobe} selects from {nelements} elements. duration={sw.ElapsedMilliseconds}");
        }
Пример #35
0
        private void ThreadStreamFunc()
        {
            int queueIndex = 0;

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Restart();
            while (!this.streamWorkerEnd)
            {
                // Determine which SoundInstance to update
                SoundInstance sndInst;
                lock (this.streamWorkerQueue)
                {
                    if (this.streamWorkerQueue.Count > 0)
                    {
                        int count = this.streamWorkerQueue.Count;
                        queueIndex = (queueIndex + count) % count;
                        sndInst    = this.streamWorkerQueue[queueIndex];
                        queueIndex = (queueIndex + count - 1) % count;
                    }
                    else
                    {
                        sndInst    = null;
                        queueIndex = 0;
                    }
                }

                // If there is no SoundInstance available, wait for a signal of one being added.
                if (sndInst == null)
                {
                    // Timeout of 100 ms to check regularly for requesting the thread to end.
                    streamWorkerQueueEvent.WaitOne(100);
                    continue;
                }

                // Perform the necessary streaming operations on the SoundInstance, and remove it when requested
                if (!sndInst.PerformStreaming())
                {
                    lock (this.streamWorkerQueue)
                    {
                        this.streamWorkerQueue.Remove(sndInst);
                    }
                }

                // After each roundtrip, sleep a little, don't keep the processor busy for no reason
                if (queueIndex == 0)
                {
                    watch.Stop();
                    int roundtripTime = (int)watch.ElapsedMilliseconds;
                    if (roundtripTime <= 1)
                    {
                        streamWorkerQueueEvent.WaitOne(16);
                    }
                    watch.Restart();
                }
            }
        }
Пример #36
0
        static void Main1(string[] args)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            var testlist = new TestList();

            testlist.xxxx = "ljcsadfasdfasdfasdddddddddddddddddddddddddddddd";
            testlist.de   = 1;
            testlist.tr   = 1;
            var ddd = BitConverter.GetBytes(testlist.de);


            sw.Restart();
            byte[] probufbytes = null;
            for (int i = 0; i < 100000; i++)
            {
                System.IO.MemoryStream ms = new MemoryStream();
                ProtoBuf.Serializer.Serialize(ms, testlist);
                probufbytes = ms.ToArray();
                ms.Close();
            }
            sw.Stop();
            Console.WriteLine("protobuf序列化总共用时:" + sw.ElapsedMilliseconds);
            var bb = LJC.FrameWork.Comm.GZip.Compress(probufbytes);

            sw.Restart();
            for (int i = 0; i < 10000; i++)
            {
                System.IO.MemoryStream ms = new MemoryStream(probufbytes);
                var pobj = ProtoBuf.Serializer.Deserialize <TestList>(ms);
                ms.Close();
            }
            sw.Stop();
            Console.WriteLine("protobuf反序列化总共用时:" + sw.ElapsedMilliseconds);


            sw.Restart();
            byte[] bytes = null;
            for (int i = 0; i < 100000; i++)
            {
                bytes = LJC.FrameWork.EntityBuf.EntityBufCore.Serialize(testlist, false);
            }
            sw.Stop();
            Console.WriteLine("序列化总共用时:" + sw.ElapsedMilliseconds);
            sw.Restart();
            TestList dlist;

            for (int i = 0; i < 10000; i++)
            {
                dlist = LJC.FrameWork.EntityBuf.EntityBufCore.DeSerialize <TestList>(bytes, false);
            }
            sw.Stop();
            Console.WriteLine("反序列化总共用时:" + sw.ElapsedMilliseconds);

            Console.Read();
        }
Пример #37
0
        private void BGW_CamRestarter_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!IC_Control.DeviceValid ||
                   (STW_fps.Elapsed.TotalMilliseconds > 1000))
            {
                int i_rem = -1;
                for (int i = 0; i < IC_Control.Devices.Count(); i++)
                {
                    if (Device_name == IC_Control.Devices[i].ToString())
                    {
                        Device_name = IC_Control.Devices[i].ToString();
                        i_rem       = i;
                        break;
                    }
                }
                if (i_rem != -1)
                {
                    try
                    {
                        IC_Control.Device = Device_name;
                    }
                    catch (Exception exc)
                    {
                        IC_Control.LiveStop();
                        IC_Control.Device = Device_name;
                    }


                    if (Device_state != null)
                    {
                        this.Dispatcher.BeginInvoke((Action)(() => IC_Control.LoadDeviceState(Device_state, true)));
                    }
                    //this.BeginInvoke((Action)(() => IC_Control.LiveStop()));
                    while (!IC_Control.LiveVideoRunning)
                    {
                        System.Threading.Thread.Sleep(200);
                        this.Dispatcher.BeginInvoke((Action)(() => IC_Control.LiveStart()));
                        RestartAttempts = 0;
                    }
                    STW_fps.Restart();
                    FLog.Log("Camera restarted!");
                }
            }
            //this.BeginInvoke((Action)(() => this.Text = "Device state: " + (IC_Control.DeviceValid ? "valid" : "invalid")));
            this.Dispatcher.BeginInvoke((Action)(() => FLog.Log("Device state: " + (IC_Control.DeviceValid ? "valid" : "invalid"))));
            Camera_restart_need = false;
            STW_fps.Restart();
        }
        //[TestMethod] // commented not to take too much time during tests run
        public void DomaticPartitionTestPerf()
        {
            var stopwatch = new System.Diagnostics.Stopwatch();
            int maxVertexCount = 16, statRetriesCount = 5;

            for (int curVertexCount = 0; curVertexCount < maxVertexCount; curVertexCount++)
            {
                double meanTime = 0;
                for (int j = 0; j < statRetriesCount; j++)
                {
                    var   graph              = generateGraph(curVertexCount);
                    int[] vertices           = graph.Item1;
                    Tuple <int, int>[] edges = graph.Item2;

                    stopwatch.Restart();
                    var partition = GetMaxDomaticPartition(vertices, edges);
                    stopwatch.Stop();

                    meanTime += stopwatch.Elapsed.TotalSeconds;
                }
                meanTime /= statRetriesCount;

                Console.WriteLine("Mean time on " + curVertexCount + " vertices = " + meanTime);
            }
        }
Пример #39
0
        private void DrawingCanvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            double positionX = e.GetPosition(this).X;

            if (mMode == MouseMode.VIEW)
            {
                int len = drawingCanvas.AllDatas[0].EndIndex - drawingCanvas.AllDatas[0].StartIndex + 1;
                if (positionX > x0 && positionX < x0 + mWidth && Math.Abs(positionX - preMoved) >= mWidth / len)
                {
                    //计算速度鼠标移动速度,如果速度过快 ,则不绘制
                    if (stopwatch.IsRunning)
                    {
                        stopwatch.Stop();
                    }
                    long curTime = stopwatch.ElapsedTicks;
                    //Console.WriteLine(curTime);
                    if (curTime > MIN_TIME)
                    {
                        this.PolyText(positionX);
                    }
                    stopwatch.Restart();
                    preMoved = positionX;
                }
            }
            else if (isMouseDown && startDown > x0 && startDown < mWidth + x0)
            {
                isMouseMoved = true;
                this.PolyRect(startDown, positionX);
            }


            //stopwatch.Start();
        }
Пример #40
0
 public void Record(string name)
 {
     Sw.Stop();
     Results.Add($"{Index}_{name}", Sw.Elapsed.TotalMilliseconds);
     Index++;
     Sw.Restart();
 }
Пример #41
0
        private void btnDecompress_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            var archive = new ExtendedArchive(textBox1.Text);

            string dir = Path.Combine(Path.GetDirectoryName(textBox1.Text), Path.GetFileNameWithoutExtension(textBox1.Text));

            Directory.CreateDirectory(dir);

            sw.Stop();
            MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());
            sw.Restart();

            foreach (var file in archive.ArchiveFiles)
            {
                string filename = dir + "\\" + file.Name;
                using (FileStream fs = new FileStream(filename, FileMode.Create))
                    using (Stream source = file.GetStream())
                    {
                        source.CopyTo(fs);
                    }
            }

            sw.Stop();

            MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());
        }
Пример #42
0
            public bool GetProcessorLoadSinceLastMeasurement(out double rate)
            {
                var process = Process.GetCurrentProcess();

                // we didn't have our first measurement yet.
                // capture current processor time and return nothing
                if (!_watch.IsRunning)
                {
                    _watch.Start();
                    _lastProcessorTime = process.TotalProcessorTime;
                    rate = 0;
                    return(false);
                }
                // calculate, how much processor time did we use since the last check
                var currentProcessorTime = process.TotalProcessorTime;
                var usedProcessor        = (currentProcessorTime - _lastProcessorTime).TotalMilliseconds;
                // task might not be called at even intervals, so we divide by time to get the rate
                var elapsedTime = _watch.ElapsedMilliseconds;

                rate = usedProcessor / elapsedTime;

                _watch.Restart();
                _lastProcessorTime = currentProcessorTime;

                return(true);
            }
Пример #43
0
        bool bRefreshOnce = true; // This is used to refresh effect between Row-Type and Fw-Type change or layout light level change
        public bool UpdateDevice(Dictionary <DeviceKeys, Color> keyColors, DoWorkEventArgs e, bool forced = false)
        {
            if (e.Cancel)
            {
                return(false);
            }

            bool update_result = false;

            watch.Restart();


            //Alpha necessary for Global Brightness modifier
            var adjustedColors = keyColors.Select(kc => AdjustBrightness(kc));

            keyboard?.SetEffect(0x32, 0x00, bRefreshOnce, adjustedColors, e);

            bRefreshOnce = false;

            watch.Stop();

            lastUpdateTime = watch.ElapsedMilliseconds;

            return(update_result);
        }
Пример #44
0
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            Z.MainForm = new Form1();
            Z.sit      = -1;
            Z.MainForm.Show();
            Z.MainForm.drawoll();
            set_curs();
            if (Z.sit != -2)
            {
                Z.sit = 1;
            }

            Z.clwidth  = Z.MainForm.ClientSize.Width;
            Z.clheight = Z.MainForm.ClientSize.Height;
            var ticktim = new System.Diagnostics.Stopwatch();

            ticktim.Start();
            while (Z.MainForm.Created)
            {
                Z.MainForm.drawoll();
                Application.DoEvents();
                if (MainGame.sit == 0)
                {
                    MainGame.prd(ticktim.ElapsedMilliseconds);
                }
                if (Z.sit == 1 || Z.sit == 2)
                {
                    MainGame.menuprd();
                }
                ticktim.Restart();
            }
        }
Пример #45
0
        private static void runFile(string filename, int times = 1)
        {
            Console.WriteLine("Processing file: " + filename);
            var f  = new FileStream(filename, FileMode.Open, FileAccess.Read);
            var sr = new StreamReader(f);
            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            var s = new Module(filename, sr.ReadToEnd());

            s.ModuleResolversChain.Add(new ModuleResolver());
            sr.Dispose();
            f.Dispose();
            sw.Stop();
            Console.WriteLine("Compile time: " + sw.Elapsed);
            Console.WriteLine("-------------------------------------");
            sw.Restart();
            while (times-- > 0)
            {
                s.Run();
            }
            sw.Stop();
            Console.WriteLine("-------------------------------------");
            Console.WriteLine("Complite.");
            Console.WriteLine("Time: " + sw.Elapsed);
        }
Пример #46
0
        public static Dictionary <string, WeiboUserInfo> GetUIDByNameList(Action <int, UserProcessModel> processChange, params string[] names)
        {
            Dictionary <string, WeiboUserInfo> result = new Dictionary <string, WeiboUserInfo>();

            try
            {
                int i = 0;
                System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                foreach (var name in names)
                {
                    ++i;
                    stopwatch.Restart();
                    result.AddOrUpdate(name, SearchWeibo(name));
                    stopwatch.Stop();
                    processChange(i, new UserProcessModel()
                    {
                        ProcessNum = i, ProcessStr = $"正在获取{name}所对应的数据", ReportStr = $"获取{name}所对应的数据耗时{stopwatch.Elapsed.TotalSeconds}秒\r\n"
                    });
                }
            }
            catch (Exception ex)
            {
            }
            return(result);
        }
Пример #47
0
 private void group1_Tick(object sender, EventArgs e)
 {
     label13.Text = dat2.tempiratura.ToString();
     if (dat2.tempiratura >= 90)
     {
         group1.Enabled = false;
         group2.Enabled = false;
         group3.Enabled = false;
         heatingTime    = 0;
         sw.Restart();
         timer3.Start();
         timer4.Stop();
         StartCooling();
     }
     group1.Interval = 240;
 }
        private static void OnRenderFrame()
        {
            // calculate how much time has elapsed since the last frame
            watch.Stop();
            float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency;

            watch.Restart();

            Matrix4 modelMatrix = CreateModelMatrix(time_);

            time_ += deltaTime;
            effect_.update(deltaTime, Neutrino._math.vec3_(modelMatrix[3].x, modelMatrix[3].y, modelMatrix[3].z), null);

            // set up the OpenGL viewport and clear both the color and depth bits
            Gl.Viewport(0, 0, width, height);
            //Gl.ClearColor(0.5F, 0.5F, 0.5F, 0.0F);
            Gl.ClearColor(0.4F, 0.4F, 0.4F, 0.0F);
            Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            Matrix4 projMatrix = Matrix4.CreatePerspectiveFieldOfView(60F * (float)Math.PI / 180F, (float)width / height, 1F, 10000F);             //.CreateOrthographic(width, height, 1F, 10000F);
            Matrix4 viewMatrix = Matrix4.LookAt(new Vector3(0, 0, 1000), Vector3.Zero, Vector3.Up);

            effect_.render(ref projMatrix, ref viewMatrix, ref modelMatrix);

            Glut.glutSwapBuffers();
        }
Пример #49
0
    public void Begin(string sectionLabel)
    {
        if (current == root)
        {
            watch.Restart();
        }

        Debug.Assert(current != null);
        Node beginNode = null;

        for (int i = 0; i < current.children.Count; i++)
        {
            if (current.children[i].label == sectionLabel)
            {
                beginNode = current.children[i];
                break;
            }
        }
        if (beginNode == null)
        {
            beginNode = new Node(sectionLabel, current);
            current.children.Add(beginNode);
        }

        Debug.Assert(beginNode.currentCallTicks0 == -1);
        beginNode.currentCallTicks0 = watch.ElapsedTicks;
        current = beginNode;
        UnityEngine.Profiling.Profiler.BeginSample(sectionLabel);
    }
        // ================================================================================
        override protected byte[] Execute(byte[] iCommand)
        {
            NetworkStream ns = Stream;

            ns.Write(iCommand, 0, iCommand.Length);
            ns.Flush();

            _watch.Restart();

            using (var ms = new MemoryStream()) {
                var buff = new byte[256];
                do
                {
                    int sz = ns.Read(buff, 0, buff.Length);
                    if (sz == 0)
                    {
                        Debug.WriteLine("读TCP流失败,网络已断");
                    }
                    else
                    {
                        ms.Write(buff, 0, sz);
                    }
                } while (ns.DataAvailable && _watch.ElapsedMilliseconds > 10);

                return(ms.ToArray());
            }
        }
 private void CompositionTargetRendering(object sender, EventArgs e)
 {
     if (!viewModel.isConnectSet() || viewModel.vm_Stop)
     {
         stopwatch.Stop();
     }
     else
     {
         if (!stopwatch.IsRunning)
         {
             stopwatch.Start();
         }
         // update graphs info
         viewModel.UpdateDateLine(viewModel.PlotModel, viewModel.ChosenChunk, ref viewModel.lastUpdate);
         viewModel.UpdateDateLine(viewModel.PlotModel_corr, viewModel.CorrelatedChunk, ref viewModel.lastUpdateCorr);
         viewModel.updateRegLine();
         // if 800 milliseconds passed - refresh graphs graphic.
         if (stopwatch.ElapsedMilliseconds > 800)
         {
             Plot1.RefreshPlot(true);
             Plot_corr.RefreshPlot(true);
             Plot_reg.RefreshPlot(true);
             stopwatch.Restart();
         }
     }
 }
Пример #52
0
        internal static void TimeInvoke(this EventHandler events, object sender, EventArgs args)
        {
            var sw = new Diagnostics.Stopwatch();

            foreach (var ev in events.GetInvocationList())
            {
                try {
                    sw.Restart();
                    ((EventHandler)ev)(sender, args);
                    sw.Stop();

                    lock (timings) {
                        if (!timings.TryGetValue(sender, out var timingPair))
                        {
                            timings [sender] = timingPair = new Dictionary <MethodInfo, TimeSpan> (MethodInfoEqualityComparer.Instance);
                        }

                        if (!timingPair.TryGetValue(ev.Method, out var previousTime))
                        {
                            previousTime = TimeSpan.Zero;
                        }

                        timingPair [ev.Method] = previousTime.Add(sw.Elapsed);
                    }
                } catch (Exception ex) {
                    LoggingService.LogInternalError(ex);
                }
            }
        }
Пример #53
0
        public bool UpdateDevice(DeviceColorComposition colorComposition, bool forced = false)
        {
            watch.Restart();

            // Connect if needed
            if (!isConnected)
            {
                Connect();
            }

            // Reduce sending based on user config
            if (!sw.IsRunning)
            {
                sw.Start();
            }

            if (sw.ElapsedMilliseconds > Global.Configuration.VarRegistry.GetVariable <int>($"{devicename}_send_delay"))
            {
                Color averageColor = Utils.BitmapUtils.GetRegionColor(
                    colorComposition.keyBitmap,
                    new BitmapRectangle(0, 0, colorComposition.keyBitmap.Width, colorComposition.keyBitmap.Height)
                    );

                SendColorsToOrb(averageColor.R, averageColor.G, averageColor.B);
                sw.Restart();
            }

            watch.Stop();
            lastUpdateTime = watch.ElapsedMilliseconds;

            return(true);
        }
Пример #54
0
        /// <summary>
        /// Show the notification window if it is not already visible.
        /// If the window is currently disappearing, it is shown again.
        /// </summary>
        public void Popup()
        {
            if (!disposed)
            {
                if (!frmPopup.Visible)
                {
                    frmPopup.Size = Size;
                    if (Scroll)
                    {
                        posStart = Screen.PrimaryScreen.WorkingArea.Bottom;
                        posStop  = Screen.PrimaryScreen.WorkingArea.Bottom - frmPopup.Height;
                    }
                    else
                    {
                        posStart = Screen.PrimaryScreen.WorkingArea.Bottom - frmPopup.Height;
                        posStop  = Screen.PrimaryScreen.WorkingArea.Bottom - frmPopup.Height;
                    }
                    opacityStart = 0;
                    opacityStop  = 1;

                    frmPopup.Opacity  = opacityStart;
                    frmPopup.Location = new Point(Screen.PrimaryScreen.WorkingArea.Right - frmPopup.Size.Width - 1, posStart);
                    frmPopup.Visible  = true;
                    isAppearing       = true;

                    tmrWait.Interval      = Delay;
                    tmrAnimation.Interval = AnimationInterval;
                    realAnimationDuration = AnimationDuration;
                    tmrAnimation.Start();
                    sw = System.Diagnostics.Stopwatch.StartNew();
                    System.Diagnostics.Debug.WriteLine("Animation started.");
                }
                else
                {
                    if (!isAppearing)
                    {
                        frmPopup.Size = Size;
                        if (Scroll)
                        {
                            posStart = frmPopup.Top;
                            posStop  = Screen.PrimaryScreen.WorkingArea.Bottom - frmPopup.Height;
                        }
                        else
                        {
                            posStart = Screen.PrimaryScreen.WorkingArea.Bottom - frmPopup.Height;
                            posStop  = Screen.PrimaryScreen.WorkingArea.Bottom - frmPopup.Height;
                        }
                        opacityStart          = frmPopup.Opacity;
                        opacityStop           = 1;
                        isAppearing           = true;
                        realAnimationDuration = Math.Max(20, 1);
                        realAnimationDuration = Math.Max((int)sw.ElapsedMilliseconds, 1);
                        sw.Restart();
                        System.Diagnostics.Debug.WriteLine("Animation direction changed.");
                    }
                    frmPopup.Invalidate();
                }
            }
        }
Пример #55
0
 private static System.Diagnostics.Stopwatch GetWatch()
 {
     if (mWatch == null)
     {
         mWatch = new Stopwatch();
         mWatch.Restart();
     }
     return(mWatch);
 }
Пример #56
0
 static void watcher_Changed(object sender, FileSystemEventArgs e)
 {
     if (sw.ElapsedMilliseconds < 100)
     {
         return;
     }
     needsBuild.Set();
     sw.Restart();
 }
Пример #57
0
        private static void OnRenderFrame()
        {
            watch.Stop();
            float DeltaTime = (float)watch.ElapsedTicks / (System.Diagnostics.Stopwatch.Frequency);

            watch.Restart();


            Shader_Program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(PosX, 0, PosZ), new Vector3(PosX + Math.Sin(TurnAngle), 0, PosZ + Math.Cos(TurnAngle)), Vector3.Up));

            Gl.Viewport(0, 0, CurrentWidth, CurrentHeight);
            Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            Gl.UseProgram(Shader_Program);
            Gl.BindTexture(Texture1);

            /*
             * foreach (var Objects in Object_List)
             * {
             *
             *  Shader_Program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(0, 0, 0)));
             *  Gl.BindBufferToShaderAttribute(Objects.Cube, Shader_Program, "vertexPosition");
             *  Gl.BindBufferToShaderAttribute(Objects.CubeUV, Shader_Program, "vertexUV");
             *  Gl.BindBuffer(Objects.CubeQuads);
             *
             *  Gl.DrawElements(BeginMode.Quads, Objects.CubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
             * }*/
            Shader_Program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(0, 0, 0)));
            Gl.BindBufferToShaderAttribute(Floor.Cube, Shader_Program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(Floor.CubeUV, Shader_Program, "vertexUV");
            Gl.BindBuffer(Floor.CubeQuads);

            Gl.DrawElements(BeginMode.Quads, Floor.CubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            Gl.BindTexture(Texture2);

            Shader_Program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(0, 0, 0)));
            Gl.BindBufferToShaderAttribute(Box.Cube, Shader_Program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(Box.CubeUV, Shader_Program, "vertexUV");
            Gl.BindBuffer(Box.CubeQuads);

            Gl.DrawElements(BeginMode.Quads, Box.CubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            // draw my cube
            //Shader_Program["model_matrix"].SetValue(Matrix4.CreateRotationX(xangle) * Matrix4.CreateRotationY(yangle) * Matrix4.CreateRotationZ(zangle));

            /*Shader_Program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(0,0,0)));
             * Gl.BindBufferToShaderAttribute(Floor.Cube, Shader_Program, "vertexPosition");
             * Gl.BindBufferToShaderAttribute(Floor.CubeUV, Shader_Program, "vertexUV");
             * Gl.BindBuffer(Floor.CubeQuads);
             *
             * Gl.DrawElements(BeginMode.Quads, Floor.CubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
             */


            Glut.glutSwapBuffers();
        }
Пример #58
0
        private void BigDataSetButton_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();

            int[] numberOfPoints = new int[] { 100, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, int.MaxValue };

            var mainPoints = GetRandomArray();

            for (int i = 0; i < numberOfPoints.Length; i++)
            {
                string query = string.Empty;

                //***********************************Earthquake
                //if (numberOfPoints[i] == int.MaxValue)
                //{
                //    query = "SELECT lat,_long FROM Earthquakes";
                //}
                //else
                //{
                //    query = "SELECT top(" + numberOfPoints[i] + ") lat,_long FROM Earthquakes";
                //}

                ////read the points
                //SqlServerDataSource source = new SqlServerDataSource("data source=.;integrated security=true;initial catalog = IRI.Database", "Earthquakes", "Location");
                //var points = source.SelectFeatures(query).Select(d => new IRI.Msh.Common.Primitives.Point((double)d["lat"], (double)d["_long"])).ToArray();

                //***********************************waze
                //if (numberOfPoints[i] == int.MaxValue)
                //{
                //    query = "SELECT Latitude,Longitude FROM Users";
                //}
                //else
                //{
                //    query = "SELECT top(" + numberOfPoints[i] + ") Latitude,Longitude FROM Users";
                //}

                //SqlServerDataSource source = new SqlServerDataSource("data source=.;integrated security=true;initial catalog = WaseDb", "Users", "Location");
                //var points = source.SelectFeatures(query).Select(d => new IRI.Msh.Common.Primitives.Point((double)d["Latitude"], (double)d["Longitude"])).ToArray();



                //***********************************random
                var points = mainPoints.Take(numberOfPoints[i] == int.MaxValue ? mainPoints.Length : numberOfPoints[i]).ToArray();

                watch.Restart();

                //order the points
                IRI.Ket.Spatial.PointSorting.PointOrdering.HilbertSorter(points);
                //IRI.Ket.DataStructure.SortAlgorithm.MergeSort(points, (p1, p2) => p1.X.CompareTo(p2.X));

                watch.Stop();
                Debug.WriteLine($"{points.Count()}, {watch.ElapsedMilliseconds / 1000.0}");
            }

            ////show result
        }
Пример #59
0
    static void CommandT2Serial(CommandArg[] args)
    {
        var terrain = FindObjectOfType <TerrainManager>();
        var sd      = new SD.Stopwatch();

        sd.Restart();
        byte[] data = terrain.SerializeTerrainV2();
        sd.Stop();
        Log($"V2 took {sd.ElapsedMilliseconds} to serialize");
    }
Пример #60
0
        private async Task UpdateDividend()
        {
            Stopwatch sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            this.txtUpdateStatus.Text  = "";
            this.txtUpdateStatus.Text += "配当利回り取得開始" + Environment.NewLine;
            // 情報の取得
            List <Utility.DividendEntity> list = new List <Utility.DividendEntity>();
            await Task.Run(() =>
            {
                Utility.FinanceUtil finance = new Utility.FinanceUtil();
                list = finance.GetDividendEntityList();
            });

            sw.Stop();
            this.txtUpdateStatus.Text += "配当利回り取得終了 " + sw.Elapsed.ToString() + Environment.NewLine;

            sw.Restart();
            this.txtUpdateStatus.Text += "配当利回り更新開始" + Environment.NewLine;
            await Task.Run(() =>
            {
                using (Utility.DbUtil db = new Utility.DbUtil())
                {
                    // 削除
                    db.DBExecuteSQL("DELETE FROM dividend");
                    // 登録
                    string insertSql = @"INSERT INTO dividend
                                    ( 
                                      OrderNo             
                                     ,StockCode           
                                     ,Market             
                                     ,CompanyName          
                                     ,Dividend             
                                     ,DividendYield              
                                     ,DetailUrl
                                    ) VALUES (
                                      :OrderNo             
                                     ,:StockCode           
                                     ,:Market             
                                     ,:CompanyName          
                                     ,:Dividend             
                                     ,:DividendYield              
                                     ,:DetailUrl
                                    )";

                    db.DBInsert(insertSql, list);

                    db.DBExecuteSQL("DELETE FROM dividend WHERE StockCode NOT IN (SELECT TargetStockCode From targetcode) ");
                }
            });

            sw.Stop();
            this.txtUpdateStatus.Text += "配当利回り更新終了 " + sw.Elapsed.ToString() + Environment.NewLine;
        }