예제 #1
0
        static void Main(string[] args)
        {
            string s = System.IO.File.ReadAllText(@"example.json");
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            for (int i = 0; i < 10000; i++)
                Fairytale.JsonDeserializer.Deserialize(s);
            
            sw.Stop();
            Console.WriteLine(sw.Elapsed);

            sw.Reset();

            sw.Start();

            for (int i = 0; i < 10000; i++)
                Newtonsoft.Json.JsonConvert.DeserializeObject(s);

            sw.Stop();
            Console.WriteLine(sw.Elapsed);

            sw.Reset();

            sw.Start();

            var parser = new System.Text.Json.JsonParser();
            for (int i = 0; i < 10000; i++)
                parser.Parse(s);

            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.ReadLine();
        }
예제 #2
0
        public void MeasureStopwatch()
        {
            var sw = new System.Diagnostics.Stopwatch();
            var measured = new System.Diagnostics.Stopwatch();
            sw.Reset();
            sw.Start();
            measured.Start();
            measured.Stop();
            var warmupTemp = measured.ElapsedMilliseconds;
            sw.Stop();
            var warmupTime = sw.ElapsedMilliseconds;
            measured.Reset();
            sw.Reset();

            sw.Start();
            sw.Stop();
            var originalTime = sw.ElapsedMilliseconds;
            sw.Reset();

            sw.Start();
            for (var i = 0; i < 1000000; i++)
            {
                measured.Start();
                measured.Stop();
                var temp = measured.ElapsedMilliseconds;
            }
            sw.Stop();
            var measuredTime = sw.ElapsedMilliseconds;
            Console.WriteLine(measuredTime - originalTime);
        }
예제 #3
0
        static void Main(string[] args)
        {

            TwitchPlays.ChannelName = "fluzzarn";
            TwitchPlays.NickName = "Fluzzarn";
            TwitchPlays.Password = Password.OAuthPWord;
            TwitchPlays.ServerAddress = "irc.twitch.tv";

            TwitchPlays.Connect();
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();

            kappa k = printKapps;
            TwitchPlays.AddCommandToFunction("Kappa",printKapps);
            TwitchPlays.AddCommandToFunction("exit", quit);
            TwitchPlays.AddCommandToFunction("quit", quit);
            while(true)
            {
                if(timer.ElapsedMilliseconds > 5000)
                {

                    string command = TwitchPlays.GetMostCommonCommand();
                    int amount = TwitchPlays.GetFrequencyOfCommand(command);
                    Console.WriteLine("Most common input was: " + command + " with " + amount + " instances");
                    TwitchPlays.ExecuteCommand(command);
                    TwitchPlays.ClearCommands();
                    timer.Reset();
                    timer.Start();
                }


            }
        }
예제 #4
0
        public void StartTest(int times)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();//引用stopwatch物件
            double avgCostTime = 0;

            for (int t = 0; t < times; t++)
            {
                sw.Reset();
                sw.Start();

                TO.Optimization();

                sw.Stop();

                string costTime = sw.Elapsed.TotalMilliseconds.ToString();
                avgCostTime += System.Convert.ToDouble(costTime);

                List<string> record = TO.GetRecord_GA();
                string result = record[record.Count - 1];
                results.Add(result);
                /*foreach (string re in record)
                {
                    this.dataGridView1.Rows[this.dataGridView1.Rows.Add()].Cells[0].Value = re;
                }*/
                int row = this.dataGridView1.Rows.Add();
                this.dataGridView1.Rows[row].Cells[0].Value = result;
                this.dataGridView1.Rows[row].Cells[1].Value = costTime;
            }

            avgCostTime = Math.Round(avgCostTime /= times, 0, MidpointRounding.AwayFromZero);
            int row2 = this.dataGridView1.Rows.Add();
            this.dataGridView1.Rows[row2].Cells[0].Value = "Avg";
            this.dataGridView1.Rows[row2].Cells[1].Value = avgCostTime;
        }
예제 #5
0
        static private void WorkerEvents()
        {
            Tuple<EventDelegate, Effect, Effect> cEvent;
			System.Diagnostics.Stopwatch cWatch = new System.Diagnostics.Stopwatch();
			while (true)
			{
				try
				{
					cEvent = _aqEvents.Dequeue();
					cWatch.Reset();
					cWatch.Restart();
					cEvent.Item1(cEvent.Item2, cEvent.Item3);
					(new Logger()).WriteDebug3("event sended [hc = " + cEvent.Item3.GetHashCode() + "][" + cEvent.Item1.Method.Name + "]");
					cWatch.Stop();
					if (40 < cWatch.ElapsedMilliseconds)
						(new Logger()).WriteDebug3("duration: " + cWatch.ElapsedMilliseconds + " queue: " + _aqEvents.nCount);
					if (0 < _aqEvents.nCount)
						(new Logger()).WriteDebug3(" queue: " + _aqEvents.nCount);
                }
                catch (System.Threading.ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    (new Logger()).WriteError(ex);
                }
            }
        }
예제 #6
0
        public void TestFromTxtFile(string file)
        {
            var wordUtil = new WordDict();
            var expectWordCount = 0;
            using (var sr = new StreamReader(file, Encoding.UTF8))
            {
                string line = null;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line == string.Empty) continue;
                    wordUtil.Add(line);
                    expectWordCount++;
                }
            }

            var watcher = new System.Diagnostics.Stopwatch();
            watcher.Start();
            var ms = new MemoryStream();
            wordUtil.SaveTo(ms);
            watcher.Stop();

            Console.WriteLine("build dawg elapsed time:" + watcher.Elapsed.TotalMilliseconds + "'ms");

            watcher.Reset();
            watcher.Start();
            ms.Position = 0;
            wordUtil = WordDict.LoadFrom(ms);
            watcher.Stop();
            Console.WriteLine("load dawg file elapsed time:" + watcher.Elapsed.TotalMilliseconds + "'ms");
            Assert.AreEqual(expectWordCount, wordUtil.Count);
        }
예제 #7
0
        public MainWindow()
        {
            InitializeComponent();
             double ticks = 0L;
             System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

             int frameCount = 0;

             //There is a textbox "txtTicks" which accept a millisecond value
             //And a button "btn", by clicking the button the dispatchertimer &
             //stopwatcher are started.
             _timer.Tick += (sender, e) =>
             {
            frameCount++;
            //System.Diagnostics.Debug.WriteLine(watch.ElapsedMilliseconds);
            if (watch.ElapsedMilliseconds > 1000)
            {
               _timer.Stop();
               watch.Reset();
               MessageBox.Show(string.Format("Already 1 second! FrameCount: {0}", frameCount));
               frameCount = 0;
            }
             };

             this.btn.Click += (sender, e) =>
             {
            double.TryParse(this.txtTicks.Text, out ticks);
            if (ticks != 0.0)
            {
               _timer.Interval = TimeSpan.FromMilliseconds(ticks);
            }
            _timer.Start();
            watch.Start();
             };
        }
        public void TestExecuteIntersectionQuery()
        {
            NUnit.Framework.Assert.IsTrue(System.IO.File.Exists(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp")),
                                          "Specified shapefile is not present!");

            var shp = new SharpMap.Data.Providers.ShapeFile(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp"), false, false);
            shp.Open();

            var fds = new SharpMap.Data.FeatureDataSet();
            var bbox = shp.GetExtents();
            //narrow it down
            bbox.ExpandBy(-0.425*bbox.Width, -0.425*bbox.Height);

            //Just to avoid that initial query does not impose performance penalty
            shp.DoTrueIntersectionQuery = false;
            shp.ExecuteIntersectionQuery(bbox, fds);
            fds.Tables.RemoveAt(0);

            //Perform query once more
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            shp.ExecuteIntersectionQuery(bbox, fds);
            sw.Stop();
            System.Console.WriteLine("Queried using just envelopes:\n" + fds.Tables[0].Rows.Count + " in " +
                                     sw.ElapsedMilliseconds + "ms.");
            fds.Tables.RemoveAt(0);

            shp.DoTrueIntersectionQuery = true;
            sw.Reset();
            sw.Start();
            shp.ExecuteIntersectionQuery(bbox, fds);
            sw.Stop();
            System.Console.WriteLine("Queried using prepared geometries:\n" + fds.Tables[0].Rows.Count + " in " +
                                     sw.ElapsedMilliseconds + "ms.");
        }
예제 #9
0
 protected void Page_Load( object sender, EventArgs e )
 {
     var url = ConfigurationManager.AppSettings.Get( "CLOUDANT_URL" );
     var connection = new Connection( new Uri( url ) );
     if ( !connection.ListDatabases().Contains( "gmkreports" ) )
     {
         connection.CreateDatabase( "gmkreports" );
     }
     var repository = new Repository<Report>( connection.CreateSession( "gmkreports" ) );
     var report = new Report { ID = Guid.NewGuid(), Type = 1, AccessionNumber = "123", Contents = "abcd" };
     System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
     watch.Reset();
     watch.Start();
     var id = repository.Save( report ).Id;
     var retrievedReport = repository.Get( id );
     watch.Stop();
     if ( retrievedReport.ID == report.ID && retrievedReport.Type == report.Type && retrievedReport.AccessionNumber == report.AccessionNumber && retrievedReport.Contents == report.Contents )
     {
         _label.Text = watch.ElapsedMilliseconds.ToString();
     }
     else
     {
         _label.Text = "Error";
     }
 }
예제 #10
0
 // 在一个页面流程内部,要使用多个秒表时,用名称以区分
 public static void Start( String stopwatchName )
 {
     System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
     stopwatch.Reset();
     stopwatch.Start();
     CurrentRequest.setItem( stopwatchName, stopwatch );
 }
예제 #11
0
        // functions
        static void Main(string[] args)
        {
            if (args.Length < 6 )
            {
                Console.WriteLine("Error --  not enough parameters");
                Console.WriteLine("Usage : DataImporter.exe file[path], ip, port, catalog, id, passwd");
                Console.ReadKey();
                return;
            }
            DbManager.SetConnString(string.Format("Data Source={0},{1};Initial Catalog={2};USER ID={3};PASSWORD={4}", args[1], args[2], args[3], args[4], args[5]));
            // argument가 directory면 파일을 만들고
            string listFileName = "";
            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(args[0]);
            if( dirInfo.Exists )
            {
                listFileName = args[0] + "\\data_table.lst";
                System.IO.StreamWriter listWriter = new System.IO.StreamWriter(listFileName);
                foreach ( System.IO.FileInfo fileInfo in dirInfo.GetFiles())
                {
                    if(fileInfo.Extension == ".csv" )
                    {
                        listWriter.WriteLine(fileInfo.FullName);
                    }
                }
                listWriter.Close();
            }
            else
            {
                listFileName = args[0];
            }

            // 시간 측정
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset();
            sw.Start();

            string[] dataFiles = System.IO.File.ReadAllLines(listFileName, Encoding.Default);
            if( dataFiles.Length == 0)
            {
                Console.WriteLine("Error : invalid file or directory.!");
                Console.ReadLine();
                return;
            }

            // 파일이면 해당 파일의 리스트를 읽어서 사용한다.
            System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
            FileManager.Init(string.Format("{0}\\{1}.log", System.IO.Directory.GetCurrentDirectory(), currentProcess.ProcessName));

            Parallel.For(0, dataFiles.Length, (i) =>
               {
               FileManager fileManager = new FileManager();
               fileManager.ImportToDb(dataFiles[i]);
               });

            FileManager.Release();

            sw.Stop();
            Console.WriteLine("수행시간 : {0}", sw.ElapsedMilliseconds / 1000.0f);
            Console.ReadLine();
        }
예제 #12
0
        private void button2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            label3.Text = "???ms";
            label4.Text = "Total is ";
            richTextBox1.Text = "";
            sw.Reset();
            sw.Start();
            List<int> resultList = primeNumbers.LinearSieve((int)numericUpDown1.Value, (int)numericUpDown2.Value);
            sw.Stop();
            label3.Text = (sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString();
            label4.Text = "Total is " + resultList.Count;
            sw.Start();

            string a = string.Join(",", resultList.ToArray());
                //sw.Stop();
                //Console.WriteLine((sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString());
                richTextBox1.Invoke((MethodInvoker)delegate {
                    //sw.Reset();
                    //sw.Start();
                    richTextBox1.AppendText(a);
                    sw.Stop();
                    label3.Text = label3.Text + "/" + (sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString();
                }
            );
        }
예제 #13
0
 private void _watch(int time, bool reset = true, bool forceGC = false, string tag = "")
 {
     if (WatchEvent == null) return;
     List<WatchFunction> _eventList = new List<WatchFunction>();
     foreach (WatchFunction _delegateItem in WatchEvent.GetInvocationList()) {
         _eventList.Add(_delegateItem);
     }
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     StringBuilder _sb = new StringBuilder();
     for (int j = 0; j < _eventList.Count; j++) {
         WatchFunction _watchItem = _eventList[j];
         long _memory = System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64;
         sw.Start();
         for (int k = 0; k < time; k++) {
             _watchItem();
         }
         sw.Stop();
         _memory = System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64 - _memory;
         Console.WriteLine(string.Format("{0,20}: {1,10} (spend: {2,10}, Memory: {3,10})", tag + _watchItem.Method.Name, sw.ElapsedTicks, sw.ElapsedMilliseconds + "ms", _memory / 1024 + "kb"));
         if (reset) sw.Reset();
     }
     Console.WriteLine();
     if (forceGC) {
         GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
     }
 }
예제 #14
0
파일: term.cs 프로젝트: kuyon/siren
 private void KeyDown_Enter(RichTextBox rtb)
 {
     string cmd = getCurLine(rtb);
     if (cmd.Length == 0 || cmd == "\n") {
         rtb.Text += "\n" + getPrompt();
         Scroll2Last(rtb);
         return;
     }
     int err = 0;
     string errmsg;
     #if false
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     sw.Reset(); sw.Start();
     #endif
     err = myViewer.mruby_exec(cmd, out errmsg);
     #if false
     sw.Stop();
     string result = "Time:" + sw.Elapsed.ToString() + "\n";
     #else
     string result = "";
     #endif
     if (!myViewer.mruby_isCodeBlockOpen()) {
         if (err == 0) {
             result += myViewer.mruby_p();
         }
         else {
             result += errmsg + "\n";
         }
     }
     rtb.Text += "\n" + result + getPrompt();
     //rtb.Select(rtb.TextLength - getPrompt().Length, getPrompt().Length);
     //rtb.SelectionColor = Color.LightGreen;
 }
예제 #15
0
        static void Main(string[] args)
        {
            int runLength = 10, FEC = 1000;

            //宣告要將結果存入 tsp.txt 檔案裡

            TSP ACOtsp = new TSP();

            //寫入檔案
            StreamWriter sw = new StreamWriter("test.csv");
            sw.WriteLine("case, best Value, Average, STD, average time");
            //馬錶
            System.Diagnostics.Stopwatch swt = new System.Diagnostics.Stopwatch();

            //ACObest 最好的值(越小越好);best 十次的值; 平均十次的值(/10); 標準差(best) ;平均時間(time / 10)
            double[] best = new double[10];

            for (int i = 0; i < ACOtsp.problem.Length; i++)
            {
                double bestsum = 0.0;

                double ACObest = double.MaxValue;

                    for (int k = 0; k < runLength; k++)
                    {
                        swt.Reset();
                        swt.Start();

                        ACOtsp.initDistance(i);                      //問題初始

                        ACOtsp.fitness=0;

                        //方法初始化
                        ACOtsp.Init(40, ACOtsp.distanceLength, 0, ACOtsp.distanceLength - 1/*,
                        ACOOption.RepeatableOption.Nonrepeatable, ACOOption.CycleOption.Cycle*/);
                        ACOtsp.Run(FEC);
                        // Console.WriteLine(ACOtsp.GbestFitness);

                        best[k] = ACOtsp.GBestFitness;
                        bestsum += best[k];

                        if (best[k] < ACObest)
                        {
                            ACObest = best[k];

                        }
                        //Console.WriteLine("fitness=" + ACOtsp.fitness);
                        //Console.WriteLine("fitness=" + fitness);
                        Console.WriteLine("ACObest = " + ACOtsp.GBestFitness);
                    }
                //Console.Read();
                swt.Stop();
                //碼錶出來的時間是毫秒,要轉成秒,除以1000。
                double time = (double)swt.Elapsed.TotalMilliseconds / 1000;
                Console.WriteLine(ACOtsp.problem[i] + ", " + ACObest + "," + bestsum / 10 + "," + std(best) + "," + time / 10);
                sw.WriteLine(ACOtsp.problem[i] + ", " + ACObest + "," + bestsum / 10 + "," + std(best) + "," + time / 10);

            }
            sw.Close();
        }
예제 #16
0
        public long Init(int objectsCount)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch ();
            try
            {
                watch.Reset ();
                watch.Start ();
                Random randomizer = new Random ();

                data = new int[objectsCount];
                for (int i = 0; i < data.Length; i++)
                {
                    data[i] = randomizer.Next () * (-1) * (randomizer.Next () % 2);
                }
                isInited = true;
                watch.Stop ();
                dataCopy = (int[])data.Clone ();
                Console.WriteLine ("Initialized data ({1} items) in {0} msec.", watch.ElapsedMilliseconds, data.Length);
                return watch.ElapsedMilliseconds;
            }
            catch (Exception ex)
            {
                isInited = false;
                Console.WriteLine ("Unable to initialize data: {0}", ex.Message);
                return INIT_FAILED;
            }
        }
예제 #17
0
        static private void WorkerEvents()
        {
            Tuple<EventDelegate, IPlugin> cEvent;
			System.Diagnostics.Stopwatch cWatch = new System.Diagnostics.Stopwatch();
            while (true)
            {
                try
                {
                    cEvent = _aqEvents.Dequeue();

					cWatch.Reset();
					cWatch.Restart();
					cEvent.Item1(cEvent.Item2);
					cWatch.Stop();
					if (40 < cWatch.ElapsedMilliseconds)
						(new Logger()).WriteDebug3("duration: " + cWatch.ElapsedMilliseconds + " queue: " + _aqEvents.nCount);
					if (0 < _aqEvents.nCount)
						(new Logger()).WriteDebug3(" queue: " + _aqEvents.nCount);
                }
                catch (System.Threading.ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    (new Logger()).WriteError(ex);
                }
            }
        }
예제 #18
0
파일: Program.cs 프로젝트: crissian/planets
        static void Main()
        {
            Scene scene = new Scene();
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            GameTime time = new GameTime();
            MessagePump.Run(scene.GraphicsEngine.Form, () =>
            {
                watch.Reset();
                watch.Start();

                int frameTime = 1;
                if (time.LastFrameElapsedTime.TotalMilliseconds < frameTime)
                    System.Threading.Thread.Sleep((int)(frameTime - time.LastFrameElapsedTime.TotalMilliseconds));
                scene.Update(time);
                scene.Draw();

                watch.Stop();
                time.LastFrameElapsedTime = watch.Elapsed;
                time.TotalGameTime = time.TotalGameTime + watch.Elapsed;

            });
            scene.Dispose();

            // TODO ce soir
            // frustrum culling pour la planète.
            // backface culling pour le ground.
            //
        }
예제 #19
0
        static void Main(string[] args)
        {
            //耗時計算
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset();
            sw.Start();
            Console.WriteLine("紀錄位置:"+config.logpath);
            //讀取輸入的資料
            Readinput();
            //多執行續啟動 設定執行緒續數量
            ThreadPool.SetMinThreads(config.maxThread, config.maxThread);

            foreach (string item in config.getList())
            {
                //Console.WriteLine(item);
                ThreadPool.QueueUserWorkItem(new WaitCallback(checkPing), item);
            }

            while (true)
            {
                if (config.listlen() == backcount)
                {
                    Console.WriteLine("done!");
                    Console.WriteLine("執行了{0}次", backcount.ToString());
                    Console.WriteLine("重試了{0}次", retrytimes.ToString());
                    Console.WriteLine("回應數量:{0}", existcount.ToString());
                    break;
                }
                Thread.Sleep(300);
            }
            sw.Stop();
            Console.WriteLine("耗時:{0} ms",((int)sw.Elapsed.TotalMilliseconds).ToString());
            Console.WriteLine("按下任意鍵結束...");
            Console.ReadKey();
        }
예제 #20
0
        public static void Main(string[] args)
        {
            Director.Initialize ();
            Director.Instance.GL.Context.SetClearColor(255,255,255,0);

            walker = new Walker("run.png", "run.xml");

            var scene = new Scene();
            scene.Camera.SetViewFromViewport();
            SpriteTile sprite = walker.Get("walkLeft00");

            sprite.Position = scene.Camera.CalcBounds().Center;
            sprite.CenterSprite();
            sprite.Scale = new Vector2(1,1);
            scene.AddChild(sprite);

            Director.Instance.RunWithScene(scene, true);

            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();

            int spriteOffset = 0;
            timer.Start();
            bool walkLeft = true;
            while(true) {
                if(timer.ElapsedMilliseconds > 25f) {
                    string spriteName;
                    if(walkLeft) {
                        spriteName = "walkLeft";
                        sprite.Position = new Vector2(sprite.Position.X - 10, sprite.Position.Y);
                    } else {
                        spriteName = "walkRight";
                        sprite.Position = new Vector2(sprite.Position.X + 10, sprite.Position.Y);
                    }
                    if(sprite.Position.X < 0) {
                        walkLeft = false;
                    }
                    if(sprite.Position.X > Director.Instance.GL.Context.GetViewport().Width) {
                        walkLeft = true;
                    }
                    spriteName += spriteOffset.ToString("00");

                    sprite.TileIndex2D = walker.Get(spriteName).TileIndex2D;

                    if(spriteOffset >= 8) {
                        spriteOffset = 0;
                    } else {
                        spriteOffset ++;
                    }

                    timer.Reset();
                    timer.Start();
                }

                Director.Instance.Update();
                Director.Instance.Render();
                Director.Instance.GL.Context.SwapBuffers();
                Director.Instance.PostSwap();
            }
        }
예제 #21
0
        static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch TimeMetering = new System.Diagnostics.Stopwatch();

            FindMedianSimple _FindMedianSimple = new FindMedianSimple();
            FindMedianAlgo _FindMedianAlgo = new FindMedianAlgo();

            //int size = 10000000;

            //Random New_rnd = new Random(); int[] a = new int[size];
            //for (int j = 0; j < size; j++)
            //{
            //    a[j] = New_rnd.Next(0, 999);
            //}
            //System.Array.Sort(a);

            //Random New_rnd2 = new Random(); int[] b = new int[size];
            //for (int l = 0; l < size; l++)
            //{
            //    b[l] = New_rnd.Next(0, 99999);
            //}
            //System.Array.Sort(b);

            int[] a = new int[] { 1, 2, 3, 4 };
            int[] b = new int[] { 1, 4, 5, 6};

            Console.WriteLine("Поиск спомощью сортировки (встроенная функция) :");
            //////////////****************
            TimeMetering.Start();
            double MedianRes = _FindMedianSimple.FindMedianArray_ContactArray(ref a, ref b);
            TimeMetering.Stop();
            var MiliSec = TimeMetering.Elapsed.TotalMilliseconds;
            Console.WriteLine("time:" + "\t" + "  " + MiliSec + "\t" + "median" + "\t" + " = "  + MedianRes);
            TimeMetering.Reset();
            //////////////****************
            Console.WriteLine("Поиск спомощью объединения :");
            //////////////****************
            TimeMetering.Start();
            double MedianRes2 = _FindMedianAlgo.FindMedianNewAlgo(a, b);
            TimeMetering.Stop();
            var MiliSec2 = TimeMetering.Elapsed.TotalMilliseconds;
            Console.WriteLine("time:" + "\t" + "  " + MiliSec2 + "\t" +  "median" + "\t" + " = " + MedianRes2);
            TimeMetering.Reset();
            //////////////****************
            Console.ReadKey();
        }
예제 #22
0
        static void ClickEllipses()
        {
            Random rnd = new Random();
            CDrawer can = new CDrawer();
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Reset();
            watch.Start();
            can.AddText("Random Bounding Box Ellipses : 2s", 28, 0, 0, can.ScaledWidth, can.ScaledHeight, Color.White);
            can.AddText("Random Bounding Box Ellipses : 2s", 28, 2, 2, can.ScaledWidth + 2, can.ScaledHeight + 2, Color.Black);
            while (watch.ElapsedMilliseconds < 5000)
            {
                Point p = new Point(rnd.Next(-50, can.ScaledWidth + 50), rnd.Next(-50, can.ScaledHeight - 50));
                switch (rnd.Next(6))
                {
                    case 0:
                        can.AddEllipse(p.X, p.Y, 100, 100);
                        break;
                    case 1:
                        can.AddEllipse(p.X, p.Y, 100, 100, RandColor.GetKnownColor(), rnd.Next(1, 4), RandColor.GetKnownColor());
                        break;
                    case 2:
                        can.AddPolygon(p.X, p.Y, 100, rnd.Next(3, 8));
                        break;
                    case 3:
                        can.AddPolygon(p.X, p.Y, 100, rnd.Next(3, 8), rnd.NextDouble() * Math.PI, RandColor.GetKnownColor(), 2, RandColor.GetKnownColor());
                        break;
                    case 4:
                        can.AddRectangle(p.X, p.Y, 100, 100);
                        break;
                    case 5:
                        can.AddRectangle(p.X, p.Y, 100, 100, RandColor.GetKnownColor(), rnd.Next(1, 4), RandColor.GetKnownColor());
                        break;
                    default:
                        break;
                }
                System.Threading.Thread.Sleep(100);

            }
            can.Close();

            can = new CDrawer(1000, 400, false);
            //System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Reset();
            watch.Start();
            can.AddText("Random Bounding Box Ellipses : 2s", 28, 0, 0, can.ScaledWidth, can.ScaledHeight, Color.White);
            can.AddText("Random Bounding Box Ellipses : 2s", 28, 2, 2, can.ScaledWidth + 2, can.ScaledHeight + 2, Color.Black);
            while (watch.ElapsedMilliseconds < 2000)
            {
                Point p = new Point(rnd.Next(50, can.ScaledWidth - 50), rnd.Next(50, can.ScaledHeight - 50));
                can.AddCenteredEllipse(p.X, p.Y, 100, 100, RandColor.GetKnownColor(), 2, Color.White);
                can.AddCenteredEllipse(p.X, p.Y, 5, 5, RandColor.GetKnownColor(), 1, Color.Red);
                System.Threading.Thread.Sleep(100);

            }
            can.Render();
            System.Threading.Thread.Sleep(1000);
            can.Close();
        }
예제 #23
0
        // -----------------------------------------------------------------------------------------------
        public override void Generate()
        {
            // -- quantize --
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Reset();
            stopwatch.Start();

            _data.Quantize(_contourHeights);

            stopwatch.Stop();
            addTiming("quantization", stopwatch.ElapsedMilliseconds);
            stopwatch.Reset();
            stopwatch.Start();

            _generatorPixelDelegate = alternatingContourColorMapPixelDelegate;

            // can use default generator
            DefaultGenerate();
        }
예제 #24
0
파일: Main.cs 프로젝트: ichaos/Shovel
 public static Shovel.Value MasterMindRun(Shovel.Instruction[] bytecode, List<Shovel.SourceFile> sources)
 {
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch ();
     sw.Reset ();
     sw.Start ();
     var result = Shovel.Api.TestRunVm (bytecode, sources);
     sw.Stop ();
     Console.WriteLine (sw.ElapsedMilliseconds / 1000.0);
     return result;
 }
예제 #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string left = File.ReadAllText(Server.MapPath("~/Examples/DeOfficiis.txt"));
            //string left = File.ReadAllText(Server.MapPath("~/Examples/DeOfficiis_Recombined.txt"));

            string right = File.ReadAllText(Server.MapPath("~/Examples/DeOfficiis_Altered.txt"));
            //string right = File.ReadAllText(Server.MapPath("~/Examples/DeOfficiis_Minor_Altered.txt"));
            //string right = File.ReadAllText(Server.MapPath("~/Examples/TotallyDifferent.txt"));

            GC.Collect(3, GCCollectionMode.Forced); // give the algorithm a fair shot...
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            var differences = new Differences(left, right, Differences.PerWord);

            sw.Stop();

            Repeater1.DataSource = from d in differences
                                   select new Fragment(d.Type,
                                       HttpContext.Current.Server.HtmlEncode(d.SplitPart).Replace("\n", "<br/>"), d.Position);
            Repeater1.DataBind();

            Response.Write("DocDiff took " + sw.Elapsed.TotalSeconds + " seconds<br/>");

            // This gives a code to convert LEFT into RIGHT
            // Is a revision repository, the older file would be RIGHT, and the newer be LEFT.
            sw.Reset();
            sw.Start();
            byte[] final_out = DiffCode.StorageDiffCode(differences);
            sw.Stop();
            Response.Write("DocDiff-code took " + sw.Elapsed.TotalSeconds + " seconds<br/>");

            double sizePc = ((double)final_out.Length / right.Length) * 100.0;
            Response.Write("<br/>DocDiff code size: " + (final_out.Length / 1024) + "KiB which is " + sizePc.ToString("0.0") + "% of the resulting file");
            Response.Write("<br/>diff code contains " + differences.Count() + " alterations.");

            sw.Reset();
            sw.Start();
            File.WriteAllText(Server.MapPath("~/Examples/DeOfficiis_Recombined.txt"),
                DiffCode.BuildRevision(left, DiffCode.BuildDiffCode(differences)));
            sw.Stop();
            Response.Write("<br/>Rebuild and write took " + sw.Elapsed.TotalSeconds + " seconds<br/>");
        }
예제 #26
0
        static void Main(string[] args)
        {
            //string exprString = "(a+b)*(c-d)/(e+f)";
            string exprString = "sin(x)+cos(x)*2-(9.84/2)^(a)";
            List<Token> tokens = Tokenizer.Tokenize(exprString);
            Console.WriteLine("** Tokenize **");
            tokens.ForEach(x => Console.WriteLine(x.ToString()));
            Console.WriteLine("** Analyze **");
            Node root = new Node();
            root.Parse(tokens);
            Console.WriteLine(root.ToString());
            Console.WriteLine("** Evaluate **");
            Console.WriteLine("* Parameters *");
            Dictionary<char, double> parameter = new Dictionary<char, double>()
            {
                {'a', 1.4},
                {'b', 2.8},
                {'c', 2.2},
                {'d', 2.4},
                {'e', 5.1},
                {'f', 9.7},
                {'t', Math.PI / 4},
                {'x', 2.0}
            };
            foreach (var p in parameter)
                Console.WriteLine("{0} = {1}", p.Key, p.Value);
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            List<TimeSpan> elapsedTimes = new List<TimeSpan>();
            for (int i = 0; i < 1; i++)
            {
                sw.Start();
                root.Evaluate(parameter);
                Console.WriteLine("i = " + i + ": " + root.Evaluate(parameter));
                sw.Stop();
            //                Console.WriteLine("  Elapsed Time: " + sw.Elapsed);
                elapsedTimes.Add(sw.Elapsed);
                sw.Reset();
            }
            Console.WriteLine("Average Elapsed Time: " + TimeSpan.FromMilliseconds(elapsedTimes.Average(ts => ts.Milliseconds)));

            //Expression expr = ArithmeticExpression.Expression.Parse(exprString);

            //Console.WriteLine("-- Original");
            //Console.WriteLine(exprString);
            //Console.WriteLine("-- Postorder");
            //Console.WriteLine(expr.Root.TraversePostorder());
            //Console.WriteLine();
            //Console.WriteLine("-- Inorder");
            //Console.WriteLine(expr.Root.TraverseInorder());
            //Console.WriteLine();
            //Console.WriteLine("-- Preorder");
            //Console.WriteLine(expr.Root.TraversePreorder());
            //Console.WriteLine();
            Console.ReadKey();
        }
예제 #27
0
 private void button3_Click(object sender, EventArgs e)
 {
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     label5.Text = "???ms";
     richTextBox1.Text = "???";
     sw.Reset();
     sw.Start();
     List<int> resultList = Algor.GetNumberListByArrayWithNotRemove((int)numericUpDownN.Value, (int)numericUpDownS.Value, (int)numericUpDownI.Value, (int)numericUpDownT.Value);
     sw.Stop();
     label5.Text = (sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString();
     richTextBox1.Text = string.Join(",", resultList.ToArray());
 }
예제 #28
0
 public long Sort(int[] data, ISortStrategy strategy)
 {
     if (!isInited)
     {
         throw new Exception ("Application should be initialized first!");
     }
     System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch ();
     watch.Reset ();
     watch.Start ();
     strategy.Sort (ref data);
     watch.Stop ();
     return watch.ElapsedMilliseconds;
 }
예제 #29
0
		static double[] Run (SymmetricAlgorithm algo, byte[] key, byte[] iv, int totalBlocks)
		{
			double[] result = new double[] {0.0, 0.0};
			byte[] input = new byte[iv.Length * totalBlocks];
			byte[] output = new byte[iv.Length * totalBlocks];
			Stopwatch sw = new Stopwatch ();
			algo.KeySize = key.Length << 3;
			algo.BlockSize = iv.Length << 3;
			algo.FeedbackSize = iv.Length << 3;
			using (ICryptoTransform ct = algo.CreateEncryptor (key, iv)) {
				if (ct.CanTransformMultipleBlocks) {
					sw.Reset (); sw.Start ();
					ct.TransformBlock (input, 0, input.Length, output, 0);
					sw.Stop ();
				} else {
					sw.Reset (); sw.Start ();
					for (int i = 0, q = 0; i < totalBlocks; i ++, q += iv.Length) {
						ct.TransformBlock (input, q, iv.Length, output, q);
					}
					sw.Stop ();
				}
				result[0] = sw.Elapsed.TotalSeconds;
			}
			using (ICryptoTransform ct = algo.CreateDecryptor (key, iv)) {
				if (ct.CanTransformMultipleBlocks) {
					sw.Reset (); sw.Start ();
					ct.TransformBlock (input, 0, input.Length, output, 0);
					sw.Stop ();
				} else {
					sw.Reset (); sw.Start ();
					for (int i = 0, q = 0; i < totalBlocks; i++, q += iv.Length) {
						ct.TransformBlock (input, q, iv.Length, output, q);
					}
					sw.Stop ();
				}
				result[1] = sw.Elapsed.TotalSeconds;
			}
			return result;
		}
예제 #30
0
        public void TestBasicLineSymbolizer()
        {
            var p = new SharpMap.Data.Providers.ShapeFile(@"d:\\daten\GeoFabrik\\roads.shp", false);
            var l = new SharpMap.Layers.VectorLayer("roads", p);
            //l.Style.Outline = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 5);
            l.Style.Line = new System.Drawing.Pen(System.Drawing.Color.Gold, 1);
            l.Style.EnableOutline = false;
            var m = new SharpMap.Map(new System.Drawing.Size(1440,1080)) {BackColor = System.Drawing.Color.Cornsilk};
            m.Layers.Add(l);

            m.ZoomToExtents();

            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            m.GetMap();

            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering old method: {0}ms", sw.ElapsedMilliseconds));
            sw.Reset();
            sw.Start();
            var bmp = m.GetMap();
            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering old method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("NDSRoads1.bmp");


            var cls = new SharpMap.Rendering.Symbolizer.CachedLineSymbolizer();
            //cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.PlainLineSymbolizeHandler { Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 5) });
            cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.PlainLineSymbolizeHandler { Line = new System.Drawing.Pen(System.Drawing.Color.Gold, 1) });

            l.Style.LineSymbolizer = cls;
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("NDSRoads2.bmp");

        }
예제 #31
0
        void updateRootShare(RootShare f, bool urgent)
        {
            lock (toSave)
                toSave.Clear();
            if (quitting)
            {
                return;
            }
            f.id = App.fileListDatabase.allocateId();
            ulong size = 0;

            SystemLog.addEntry("Updating root share " + f.fullPath.Replace('/', System.IO.Path.DirectorySeparatorChar) + "...");
            sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            string path = "";

            path = f.fullPath;

            bool invalidated = false;

            System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(path);
            if (d.LastWriteTimeUtc.Ticks != f.lastModified)
            {
                invalidated = true;
            }
            string s = "";

            try
            {
                if (d.GetFiles().Length + d.GetDirectories().Length != f.folderIds.Length + f.fileIds.Length)
                {
                    invalidated = true;
                }
                foreach (System.IO.FileInfo i in d.GetFiles())
                {
                    s += i.Name + "|" + i.Length.ToString() + "|" + i.LastWriteTimeUtc.Ticks.ToString() + Environment.NewLine;
                    wait(urgent);
                }
                foreach (System.IO.DirectoryInfo i in d.GetDirectories())
                {
                    s += i.Name + "|" + i.LastWriteTimeUtc.Ticks.ToString() + Environment.NewLine;
                    wait(urgent);
                }
            }
            catch (System.IO.IOException)
            {
                return;
            }
            string s2 = "";

            foreach (ulong id in f.fileIds)
            {
                File i = App.fileListDatabase.getObject <File>(App.fileListDatabase.fileList, "FSListing " + id.ToString());

                if (i != null)
                {
                    size += i.size;
                    s2   += i.name + "|" + i.size + "|" + i.lastModified.ToString() + Environment.NewLine;
                }
                wait(urgent);
            }
            foreach (ulong id in f.folderIds)
            {
                Folder i = App.fileListDatabase.getObject <Folder>(App.fileListDatabase.fileList, "FSListing " + id.ToString());

                if (i != null)
                {
                    size += i.size;
                    s2   += i.name + "|" + i.lastModified.ToString() + Environment.NewLine;
                }
                wait(urgent);
            }
            if (s != s2)
            {
                invalidated = true;
            }

            if (invalidated)
            {
                deleteFolder(f, urgent);
                size   = loadFolder(f, urgent, path);
                f.size = size;
                lock (toSave)
                    toSave["FSListing " + f.id] = f;
                if (!quitting)
                {
                    App.fileListDatabase.setObject(App.settings.settings, "Root Share " + f.index.ToString(), f);
                    doSave();
                }
            }
            sw.Stop();
            sw.Reset();
        }
예제 #32
0
        /// <summary>
        /// Begins the ingest testing.
        /// </summary>
        public void Start()
        {
            // can only run it once per instance
            if (m_TestState != TestState.Uninitalized)
            {
                return;
            }

            m_StreamCallbackListener = new StreamCallbackListener(this);
            m_StatCallbackListener   = new StatCallbackListener(this);

            m_CurrentServerIndex      = 0;
            m_CancelTest              = false;
            m_SkipServer              = false;
            m_Broadcasting            = false;
            m_WaitingForStartCallback = false;
            m_WaitingForStopCallback  = false;

            m_PreviousStatCallbacks = m_Stream.StatCallbacks;
            m_Stream.StatCallbacks  = m_StatCallbackListener;

            m_PreviousStreamCallbacks = m_Stream.StreamCallbacks;
            m_Stream.StreamCallbacks  = m_StreamCallbackListener;

            m_IngestTestVideoParams                        = new VideoParams();
            m_IngestTestVideoParams.TargetFps              = Twitch.Broadcast.Constants.TTV_MAX_FPS;
            m_IngestTestVideoParams.MaxKbps                = Twitch.Broadcast.Constants.TTV_MAX_BITRATE;
            m_IngestTestVideoParams.OutputWidth            = 1280;
            m_IngestTestVideoParams.OutputHeight           = 720;
            m_IngestTestVideoParams.PixelFormat            = PixelFormat.TTV_PF_BGRA;
            m_IngestTestVideoParams.DisableAdaptiveBitrate = true;
            m_IngestTestVideoParams.VerticalFlip           = false;

            m_Stream.GetDefaultParams(m_IngestTestVideoParams);

            m_IngestTestAudioParams = new AudioParams();
            m_IngestTestAudioParams.AudioEnabled           = false;
            m_IngestTestAudioParams.EnableMicCapture       = false;
            m_IngestTestAudioParams.EnablePlaybackCapture  = false;
            m_IngestTestAudioParams.EnablePassthroughAudio = false;

            m_IngestBuffers = new List <UIntPtr>();

            // allocate some buffers
            int numFrames = 3;

            for (int i = 0; i < numFrames; ++i)
            {
                UIntPtr buffer = UIntPtr.Zero;
                uint    size   = m_IngestTestVideoParams.OutputWidth * m_IngestTestVideoParams.OutputHeight * 4;

                m_Stream.AllocateFrameBuffer(size, out buffer);

                if (buffer == UIntPtr.Zero)
                {
                    Cleanup();
                    SetTestState(TestState.Failed);
                    return;
                }

                m_Stream.RandomizeFrameBuffer(buffer, size);

                m_IngestBuffers.Add(buffer);
            }

            SetTestState(TestState.Starting);

            m_Timer.Reset();
            m_Timer.Start();
        }
예제 #33
0
        private static void Profiling()
        {
            int dictionarysize = 10000000;

            int[] numbers = new int[dictionarysize];
            var   r       = new Random();

            for (int i = 0; i < dictionarysize; i++)
            {
                numbers[i] = r.Next();
            }

            FasterDictionary <int, Test> fasterDictionary = new FasterDictionary <int, Test>();
            Dictionary <int, Test>       dictionary       = new Dictionary <int, Test>();

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

            System.Console.WriteLine("insert");
            for (int i = 0; i < dictionarysize; i++)
            {
                dictionary[numbers[i]] = new Test(i);
            }
            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                dictionary[numbers[i]] = new Test(i);
            }
            watch.Stop();
            System.Console.WriteLine(watch.ElapsedMilliseconds);
            for (int i = 0; i < dictionarysize; i++)
            {
                fasterDictionary[numbers[i]] = new Test(i);
            }
            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                fasterDictionary[numbers[i]] = new Test(i);
            }
            watch.Stop();
            System.Console.WriteLine(watch.ElapsedMilliseconds);

/*
 *          fasterDictionary = new FasterDictionary<int, Test>();
 *          dictionary = new Dictionary<int, Test>();
 *          System.Console.WriteLine("add after new");
 *          watch.Reset();
 *          watch.Start();
 *          for (int i = 0; i < dictionarysize; i++) dictionary.Add(numbers[i], new Test(i));
 *          watch.Stop();
 *          System.Console.WriteLine(watch.ElapsedMilliseconds);
 *
 *          watch.Reset();
 *          watch.Start();
 *          for (int i = 0; i < dictionarysize; i++) fasterDictionary.Add(numbers[i], new Test(i));
 *          watch.Stop();
 *          System.Console.WriteLine(watch.ElapsedMilliseconds);
 */
            fasterDictionary = new FasterDictionary <int, Test>(dictionarysize);
            dictionary       = new Dictionary <int, Test>();
            System.Console.WriteLine("insert after new with presize");
            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                dictionary[numbers[i]] = new Test(i);
            }
            watch.Stop();
            System.Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                fasterDictionary[numbers[i]] = new Test(i);
            }
            watch.Stop();
            System.Console.WriteLine(watch.ElapsedMilliseconds);

            dictionary.Clear();
            fasterDictionary.Clear();
            System.Console.WriteLine("insert after clear");
            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                dictionary[numbers[i]] = new Test(i);
            }
            watch.Stop();
            System.Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                fasterDictionary[numbers[i]] = new Test(i);
            }
            watch.Stop();
            System.Console.WriteLine(watch.ElapsedMilliseconds);

            System.Console.WriteLine("read");

            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                Test JapaneseCalendar;
                JapaneseCalendar = dictionary[numbers[i]];
            }

            watch.Stop();

            System.Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                Test JapaneseCalendar;
                JapaneseCalendar = fasterDictionary[numbers[i]];
            }

            watch.Stop();

            System.Console.WriteLine(watch.ElapsedMilliseconds);

            System.Console.WriteLine("iterate values");

            watch.Reset();
            watch.Start();
            for (int i = 0; i < 1; i++)
            {
                Test JapaneseCalendar;
                foreach (var VARIABLE in dictionary.Values)
                {
                    JapaneseCalendar = VARIABLE;
                }
            }

            watch.Stop();

            System.Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Reset();
            watch.Start();
            for (int i = 0; i < 1; i++)
            {
                Test JapaneseCalendar;
                int  count;
                var  buffer = fasterDictionary.GetValuesArray(out count);
                for (int j = 0; j < count; j++)
                {
                    JapaneseCalendar = buffer[j];
                }
            }

            watch.Stop();

            System.Console.WriteLine(watch.ElapsedMilliseconds);

            System.Console.WriteLine("remove");
            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                dictionary.Remove(numbers[i]);
            }

            watch.Stop();

            System.Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Reset();
            watch.Start();
            for (int i = 0; i < dictionarysize; i++)
            {
                fasterDictionary.Remove(numbers[i]);
            }

            watch.Stop();

            System.Console.WriteLine(watch.ElapsedMilliseconds);
        }
예제 #34
0
        public void Run()
        {
            mRunning = true;
            int sleep = 1000 / frequency;

            using (outputfile = new System.IO.StreamWriter(Path + "\\write_test.txt"))
            {
                outputfile.WriteLine("Database: " + Program.Database + "\t Variables: " + variables + "\t Iterations: " + iterations + "\t WriteFrequency: " + frequency);
                outputfile.WriteLine("Insert duration\tFinal duration\tRead back\tSpeed");

                //Write-TestCase
                System.Console.WriteLine("Start Write-TestCase");
                telemetry = new Telemetry(Program.VmName, Path, variables, adapter);
                telemetry.InitTelemetryCollection("write");
                var w_mock      = new System.Diagnostics.Stopwatch();
                var endinittime = System.DateTime.Now.Add(inititerations);
                while (endinittime.Subtract(System.DateTime.Now).TotalSeconds > 0)
                {
                    if (!mRunning)
                    {
                        break;
                    }
                    var st = System.Diagnostics.Stopwatch.StartNew();
                    PrepareData(initvariables);
                    Send(ref w_mock);
                    st.Stop();
                    double elap = st.Elapsed.TotalSeconds;
                    int    wait = sleep - (int)(elap * 1000);
                    if (wait > 0)
                    {
                        System.Threading.Thread.Sleep(wait);
                    }
                }
                while (mRunning)
                {
                    for (int j = 0; j < iterations; j++)
                    {
                        if (!mRunning)
                        {
                            break;
                        }
                        var st = System.Diagnostics.Stopwatch.StartNew();
                        if (frequency > 1)
                        {
                            for (int i = 1; i < frequency; i++)
                            {
                                var st0 = System.Diagnostics.Stopwatch.StartNew();
                                PrepareData(variables);
                                Send(ref w_mock);
                                double elap0 = st0.Elapsed.TotalSeconds;
                                int    wait0 = sleep - (int)(elap0 * 1000);
                                if (wait0 > 0)
                                {
                                    System.Threading.Thread.Sleep(wait0);
                                }
                            }
                        }
                        var check00 = st.Elapsed.TotalSeconds;
                        PrepareData(variables);
                        var check0 = st.Elapsed.TotalSeconds;
                        Send(ref onevariable_watch);
                        var check1 = st.Elapsed.TotalSeconds;
                        while (true)
                        {
                            bool x = CheckInsert();
                            if (x)
                            {
                                break;
                            }
                            System.Threading.Thread.Sleep(100);
                        }
                        onevariable_watch.Stop();
                        st.Stop();
                        double elap    = st.Elapsed.TotalSeconds;
                        double d       = check0 - check00;
                        string logtext = "Insert duration: " + check1 + " Final duration: " + elap + " Read back: " + onevariable_watch.Elapsed.TotalSeconds + " PrepareData: " + d;
                        System.Console.WriteLine(logtext);
                        float speed = (float)(variables / elap);
                        System.Console.WriteLine("Speed: " + speed);

                        try
                        {
                            outputfile.WriteLine(check1 + "\t" + elap + "\t" + onevariable_watch.Elapsed.TotalSeconds + "\t" + speed);
                        }
                        catch (System.ObjectDisposedException) { }
                        onevariable_watch.Reset();
                        int wait = 1000 - (int)(elap * 1000);
                        if (wait > 0)
                        {
                            System.Threading.Thread.Sleep(wait);
                        }
                    }
                    if (mRunning)
                    {
                        variables += increament;                         //Increase updated variable count
                        telemetry.CollectVariableRunTelemetry(variables);
                        if (variables >= stop_value)
                        {
                            mRunning = false; break;
                        }
                        try { outputfile.WriteLine("New Variable count: " + variables + "\t"); }
                        catch (System.ObjectDisposedException) { }
                    }
                }
                telemetry.CloseVMConnection();
            }
        }
예제 #35
0
        void Update()
        {
            // prepare threads
            if (multithreaded)
            {
                if (_threadPool == null)
                {
                    _threadPool = new FogOfWarThreadPool();
                }
                threads = Mathf.Clamp(threads, 2, 8);
                _threadPool.maxThreads = threads;
                _threadPool.Clean();
            }
            else if (_threadPool != null)
            {
                _threadPool.StopAllThreads();
                _threadPool = null;
            }

            _stopwatch.Reset();
            _stopwatch.Start();

            // draw shapes
            ProcessUnits();

            // compile final texture
            _timeSinceLastUpdate += Time.deltaTime;
            if (_currentUnitProcessing >= _registeredUnits.Count && (!multithreaded || _threadPool.hasAllFinished))
            {
                _drawer.GetValues(_fogValuesCopy);
                _currentUnitProcessing = 0;

                // prepare texture
                if (fogTexture == null)
                {
                    fogTexture            = new Texture2D(mapResolution.x, mapResolution.y, TextureFormat.Alpha8, false);
                    fogTexture.wrapMode   = TextureWrapMode.Clamp;
                    fogTexture.filterMode = filterMode;
                }
                else if (fogTexture.width != mapResolution.x || fogTexture.height != mapResolution.y)
                {
                    fogTexture.Resize(mapResolution.x, mapResolution.y, TextureFormat.Alpha8, false);
                }
                else
                {
                    fogTexture.filterMode = filterMode;
                }
                fogTexture.LoadRawTextureData(_fogValuesCopy);
                fogTexture.Apply();

                // apply blur
                _finalFogTexture = _blur.Apply(fogTexture, mapResolution, blurAmount, blurIterations, blurType);

                // fade in fog
                _fadeAmount += fadeSpeed * _timeSinceLastUpdate;
                byte fadebytes = (byte)(_fadeAmount * 255);
                if (fadebytes > 0)
                {
                    _drawer.Fade((byte)(partialFogAmount * 255), fadebytes);
                    _fadeAmount -= fadebytes / 255.0f;
                }

                _timeSinceLastUpdate = 0;

                if (!_isFirstProcessingFrame)
                {
                    ProcessUnits();
                }
                _isFirstProcessingFrame = true;
            }
            else
            {
                _isFirstProcessingFrame = false;
            }

            _stopwatch.Stop();
        }
예제 #36
0
        public void Run()
        {
            CheckIfRunning();

            Stat     = Status.Running;
            IsExited = false;

#if !NET_CORE
            // 开启多线程支持
            System.Net.ServicePointManager.DefaultConnectionLimit = 1000;
#endif

            InitComponent();

            IMonitorableScheduler monitor = (IMonitorableScheduler)Scheduler;

            if (StartTime == DateTime.MinValue)
            {
                StartTime = DateTime.Now;
            }

            Parallel.For(0, ThreadNum, new ParallelOptions
            {
                MaxDegreeOfParallelism = ThreadNum
            }, i =>
            {
                int waitCount  = 0;
                bool firstTask = false;

                var downloader = Downloader.Clone();

                while (Stat == Status.Running)
                {
                    Request request = Scheduler.Poll(this);

                    if (request == null)
                    {
                        if (waitCount > _waitCountLimit && IsExitWhenComplete)
                        {
                            Stat = Status.Finished;
                            break;
                        }

                        // wait until new url added
                        WaitNewUrl(ref waitCount);
                    }
                    else
                    {
                        Log.WriteLine($"Left: {monitor.GetLeftRequestsCount(this)} Total: {monitor.GetTotalRequestsCount(this)} Thread: {ThreadNum}");

                        waitCount = 0;

                        try
                        {
                            ProcessRequest(request, downloader);
                            Thread.Sleep(Site.SleepTime);
#if TEST
                            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                            sw.Reset();
                            sw.Start();
#endif

                            OnSuccess(request);
#if TEST
                            sw.Stop();
                            Console.WriteLine("OnSuccess:" + (sw.ElapsedMilliseconds).ToString());
#endif
                        }
                        catch (Exception e)
                        {
                            OnError(request);
                            Logger.Error("采集失败: " + request.Url + ".", e);
                        }
                        finally
                        {
#if !NET_CORE
                            if (Site.HttpProxyPoolEnable && request.GetExtra(Request.Proxy) != null)
                            {
                                Site.ReturnHttpProxyToPool((HttpHost)request.GetExtra(Request.Proxy), (int)request.GetExtra(Request.StatusCode));
                            }
#endif
                            FinishedPageCount.Inc();
                        }

                        if (!firstTask)
                        {
                            Thread.Sleep(3000);
                            firstTask = true;
                        }
                    }
                }
            });

            FinishedTime = DateTime.Now;

            foreach (IPipeline pipeline in Pipelines)
            {
                SafeDestroy(pipeline);
            }

            if (Stat == Status.Finished)
            {
                OnClose();

                Logger.Info($"任务 {Identity} 结束.");
            }

            if (Stat == Status.Stopped)
            {
                Logger.Info("任务 " + Identity + " 停止成功!");
            }

            SpiderClosingEvent?.Invoke();

            Log.WaitForExit();

            if (Stat == Status.Exited)
            {
                Logger.Info("任务 " + Identity + " 退出成功!");
            }

            IsExited = true;
        }
예제 #37
0
        public void Produce(object arg)
        {
            Params p = (Params)arg;

            using (produce_outputfile = new System.IO.StreamWriter(p.Path + "\\produce.txt"))
            {
                produce_outputfile.WriteLine("Database: " + Program.Database + "\t Variables: " + p.Variables + "\t Iterations: " + p.Iterations + "\t WriteFrequency: " + p.writefrequency + "\t InitIterations: " + p.inititerations);
                produce_outputfile.WriteLine("Insert duration\tFinal duration\tRead back\tSpeed");

                telemetry_p = new Telemetry(Program.VmName, p.Path, p.Variables, adapter);
                telemetry_p.InitTelemetryCollection("produce");
                System.Diagnostics.Stopwatch onevariable_watch = new System.Diagnostics.Stopwatch();
                var w_mock = new System.Diagnostics.Stopwatch();
                int sleep  = (int)((1.0f / (double)p.writefrequency) * 1000);
                while (p_mRunning)
                {
                    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                    var startime = System.DateTime.Now;
                    var endtime  = startime.Add(p.timeSpan);
                    while (System.DateTime.Now.Subtract(endtime).TotalSeconds <= 0)
                    {
                        if (!p_mRunning)
                        {
                            break;
                        }
                        sw.Restart();
                        adapter.PrepareWriteData(p.Variables);
                        adapter.Send(ref onevariable_watch);
                        sw.Stop();
                        int wait = sleep - (int)sw.ElapsedMilliseconds;
                        if (wait > 0)
                        {
                            System.Threading.Thread.Sleep(wait);
                        }
                    }
                    while (p.Variables < max_var)
                    {
                        var percent = p.Iterations / 100;
                        for (int j = 0; j < p.Iterations; j++)
                        {
                            if (!p_mRunning)
                            {
                                break;
                            }
                            sw.Restart();
                            if (p.writefrequency > 1)
                            {
                                for (int i = 1; i < p.writefrequency; i++)
                                {
                                    var st0 = System.Diagnostics.Stopwatch.StartNew();
                                    adapter.PrepareWriteData(p.Variables);
                                    adapter.Send(ref w_mock);
                                    double elap0 = st0.Elapsed.TotalSeconds;
                                    int    wait0 = sleep - (int)(elap0 * 1000);
                                    if (wait0 > 0)
                                    {
                                        System.Threading.Thread.Sleep(wait0);
                                    }
                                }
                            }
                            adapter.PrepareWriteData(p.Variables);

                            adapter.Send(ref onevariable_watch);
                            var check1 = sw.Elapsed.TotalSeconds;
                            while (true)
                            {
                                bool x = adapter.CheckInsert();
                                if (x)
                                {
                                    break;
                                }
                                if (!p_mRunning)
                                {
                                    break;
                                }
                            }
                            onevariable_watch.Stop();
                            sw.Stop();
                            double elap  = sw.Elapsed.TotalSeconds;
                            float  speed = (float)(p.Variables / elap);
                            try
                            {
                                produce_outputfile.WriteLine(check1 + "\t" + elap + "\t" + onevariable_watch.Elapsed.TotalSeconds + "\t" + speed);
                            }
                            catch (System.ObjectDisposedException) { }
                            onevariable_watch.Reset();
                            if (j % percent == 0)
                            {
                                System.Console.WriteLine("Producer: " + j / percent + "% progress");
                            }
                            int wait = sleep - (int)sw.ElapsedMilliseconds;
                            if (wait > 0)
                            {
                                System.Threading.Thread.Sleep(wait);
                            }
                        }
                        if (p_mRunning)
                        {
                            p.Variables += increament;                             //Increase updated variable count
                            telemetry_p.CollectVariableRunTelemetry(p.Variables);
                            if (p.Variables >= max_var)
                            {
                                p_mRunning = false; break;
                            }
                            try { produce_outputfile.WriteLine("New Variable count: " + p.Variables + "\t"); }
                            catch (System.ObjectDisposedException) { }
                        }
                    }
                    p_done = true;
                    System.Console.WriteLine("Producer iterations finished");
                    telemetry_p.CollectVariableRunTelemetry(p.Variables);
                    telemetry_p.mRunning = false;
                    produce_outputfile.Flush();
                    produce_outputfile.Close();
                    produce_outputfile.Dispose();
                    System.Console.WriteLine("Producer start fill");
                    while (p_mRunning)
                    {
                        sw.Restart();
                        adapter.PrepareWriteData(p.Variables);
                        adapter.Send(ref onevariable_watch);
                        sw.Stop();
                        int wait = sleep - (int)(sw.ElapsedMilliseconds);
                        if (wait > 0)
                        {
                            System.Threading.Thread.Sleep(wait);
                        }
                    }
                    System.Console.WriteLine("Producer fill finished");
                    break;
                }
                System.Console.WriteLine("Producer ending");
            }
        }
예제 #38
0
 void Update()
 {
     stopwatch.Reset();
     stopwatch.Start();
 }
예제 #39
0
파일: Program.cs 프로젝트: wolski/RawTools
        static int DoStuff(ArgumentParser.ParseOptions opts)
        {
            List <string> files = new List <string>();

            if (opts.InputFiles.Count() > 0) // did the user give us a list of files?
            {
                List <string> problems = new List <string>();
                files = opts.InputFiles.ToList();

                // check if the list provided contains only .raw files
                foreach (string file in files)
                {
                    if (!file.EndsWith(".raw", StringComparison.OrdinalIgnoreCase))
                    {
                        problems.Add(file);
                    }
                }

                if (problems.Count() == 1)
                {
                    Console.WriteLine("\nERROR: {0} does not appear to be a .raw file. Invoke '>RawTools --help' if you need help.", problems.ElementAt(0));
                    Log.Error("Invalid file provided: {0}", problems.ElementAt(0));

                    return(1);
                }

                if (problems.Count() > 1)
                {
                    Console.WriteLine("\nERROR: The following {0} files do not appear to be .raw files. Invoke '>RawTools --help' if you need help." +
                                      "\n\n{1}", problems.Count(), String.Join("\n", problems));
                    Log.Error("Invalid files provided: {0}", String.Join(" ", problems));
                    return(1);
                }

                Log.Information("Files to be processed, provided as list: {0}", String.Join(" ", files));
            }

            else // did the user give us a directory?
            {
                if (Directory.Exists(opts.InputDirectory))
                {
                    files = Directory.GetFiles(opts.InputDirectory, "*.*", SearchOption.TopDirectoryOnly)
                            .Where(s => s.EndsWith(".raw", StringComparison.OrdinalIgnoreCase)).ToList();
                }
                else
                {
                    Console.WriteLine("ERROR: The provided directory does not appear to be valid.");
                    Log.Error("Invalid directory provided: {0}", opts.InputDirectory);
                    return(1);
                }

                Log.Information("Files to be processed, provided as directory: {0}", String.Join(" ", files));
            }

            if (opts.Quant)
            {
                List <string> possible = new List <string>()
                {
                    "TMT0", "TMT2", "TMT6", "TMT10", "TMT11", "iTRAQ4", "iTRAQ8"
                };
                if (!possible.Contains(opts.LabelingReagents))
                {
                    Console.WriteLine("ERROR: For quantification, the labeling reagent must be one of {TMT0, TMT2, TMT6, TMT10, TMT11, iTRAQ4, iTRAQ8}");
                    Log.Error("Invalid labeling reagent provided: {0}", opts.LabelingReagents);
                    return(1);
                }
            }

            if (opts.Chromatogram != null)
            {
                List <string> possible = new List <string>()
                {
                    "1T", "2T", "3T", "1B", "2B", "3B", "1TB", "2TB", "3TB", "1TB", "2TB", "3TB"
                };
                if (!possible.Contains(opts.Chromatogram))
                {
                    Console.WriteLine("ERROR: Incorrect format for --chro. See help.");
                    Log.Error("Invalid chromatogram argument provided: {Chro}", opts.Chromatogram);
                    return(1);
                }
            }

            System.Diagnostics.Stopwatch singleFileTime = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch totalTime      = new System.Diagnostics.Stopwatch();
            totalTime.Start();

            foreach (string file in files)
            {
                singleFileTime.Start();

                Console.WriteLine("\nProcessing: {0}\n", file);

                using (IRawDataPlus rawFile = RawFileReaderFactory.ReadFile(fileName: file))
                {
                    rawFile.SelectInstrument(Device.MS, 1);

                    Log.Information("Now processing: {File} --- Instrument: {Instrument}", Path.GetFileName(file), rawFile.GetInstrumentData().Name);

                    RawDataCollection   rawData   = new RawDataCollection(rawFile: rawFile);
                    QuantDataCollection quantData = new QuantDataCollection();

                    bool isBoxCar = rawData.isBoxCar;

                    if (rawData.isBoxCar)
                    {
                        Console.WriteLine("\nRaw file appears to be a boxcar-type experiment. Precursor peak analysis won't be performed!\n");
                    }

                    if (opts.ParseData | opts.Metrics | opts.Quant)
                    {
                        rawData.ExtractAll(rawFile);

                        if (!isBoxCar)
                        {
                            rawData.CalcPeakRetTimesAndInts(rawFile: rawFile);
                        }
                    }

                    if (opts.Quant)
                    {
                        rawData.quantData.Quantify(rawData: rawData, rawFile: rawFile, labelingReagent: opts.LabelingReagents);
                    }

                    if (opts.UnlabeledQuant & !isBoxCar)
                    {
                        rawData.QuantifyPrecursorPeaks(rawFile);
                    }

                    if (opts.Metrics)
                    {
                        rawData.metaData.AggregateMetaData(rawData, rawFile);
                    }

                    if (opts.ParseData | opts.Quant)
                    {
                        if (opts.Quant)
                        {
                            Parse.WriteMatrix(rawData: rawData, rawFile: rawFile, metaData: rawData.metaData, quantData: rawData.quantData, outputDirectory: opts.OutputDirectory);
                        }
                        else
                        {
                            Parse.WriteMatrix(rawData: rawData, rawFile: rawFile, metaData: rawData.metaData, outputDirectory: opts.OutputDirectory);
                        }
                    }

                    if (opts.WriteMGF)
                    {
                        MGF.WriteMGF(rawData: rawData, rawFile: rawFile, outputDirectory: opts.OutputDirectory, cutoff: opts.MassCutOff,
                                     intensityCutoff: opts.IntensityCutoff);
                    }

                    if (opts.Metrics)
                    {
                        MetricsData metricsData = new MetricsData();

                        if (opts.Quant)
                        {
                            metricsData.GetMetricsData(metaData: rawData.metaData, rawData: rawData, rawFile: rawFile, quantData: rawData.quantData);
                        }
                        else
                        {
                            metricsData.GetMetricsData(metaData: rawData.metaData, rawData: rawData, rawFile: rawFile);
                        }

                        metricsData.GetMetricsData(metaData: rawData.metaData, rawData: rawData, rawFile: rawFile);
                        Metrics.WriteMatrix(rawData, metricsData, opts.OutputDirectory);
                    }

                    if (opts.Chromatogram != null)
                    {
                        int order = Convert.ToInt32((opts.Chromatogram.ElementAt(0).ToString()));

                        if (order > (int)rawData.methodData.AnalysisOrder)
                        {
                            Log.Error("Specified MS order ({Order}) for chromatogram is higher than experiment order ({ExpOrder})",
                                      (MSOrderType)order, rawData.methodData.AnalysisOrder);
                            Console.WriteLine("Specified MS order ({0}) for chromatogram is higher than experiment order ({1}). Chromatogram(s) won't be written.",
                                              (MSOrderType)order, rawData.methodData.AnalysisOrder);
                        }
                        else
                        {
                            rawData.WriteChromatogram(rawFile, (MSOrderType)order, opts.Chromatogram.Contains("T"), opts.Chromatogram.Contains("B"), opts.OutputDirectory);
                        }
                    }
                }

                singleFileTime.Stop();
                Console.WriteLine("\nElapsed time: {0} s", Math.Round(Convert.ToDouble(singleFileTime.ElapsedMilliseconds) / 1000.0, 2));
                singleFileTime.Reset();
            }
            totalTime.Stop();
            Console.WriteLine("\nTime to process all {0} files: {1}", files.Count(), totalTime.Elapsed);

            return(0);
        }
예제 #40
0
        /// <summary>
        /// Worker thread.
        /// </summary>
        ///
        private void WorkerThread( )
        {
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch( );

            // buffer to read stream into
            byte[] buffer = new byte[bufferSize];

            while (!stopEvent.WaitOne(0, false))
            {
                try
                {
                    stopWatch.Reset( );
                    stopWatch.Start( );

                    int bytesRead = communicator.SendAndReceive(new byte[] { (byte)'I' }, buffer);

                    bytesReceived += bytesRead;

                    if (bytesRead > 10)
                    {
                        // check for image reply signature
                        if (
                            (buffer[0] == (byte)'#') &&
                            (buffer[1] == (byte)'#') &&
                            (buffer[2] == (byte)'I') &&
                            (buffer[3] == (byte)'M') &&
                            (buffer[4] == (byte)'J'))
                        {
                            // extract image size
                            int imageSize = System.BitConverter.ToInt32(buffer, 6);

                            if (!stopEvent.WaitOne(0, false))
                            {
                                try
                                {
                                    // decode image from memory stream
                                    Bitmap bitmap = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 10, imageSize));
                                    framesReceived++;

                                    // let subscribers know if there are any
                                    if (NewFrame != null)
                                    {
                                        NewFrame(this, new BestCS.Video.NewFrameEventArgs(bitmap));
                                    }

                                    bitmap.Dispose( );
                                }
                                catch
                                {
                                }

                                // wait for a while ?
                                if (frameInterval > 0)
                                {
                                    // get download duration
                                    stopWatch.Stop( );

                                    // miliseconds to sleep
                                    int msec = frameInterval - (int)stopWatch.ElapsedMilliseconds;

                                    while ((msec > 0) && (stopEvent.WaitOne(0, false) == false))
                                    {
                                        // sleeping ...
                                        Thread.Sleep((msec < 100) ? msec : 100);
                                        msec -= 100;
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                    if (VideoSourceError != null)
                    {
                        VideoSourceError(this, new BestCS.Video.VideoSourceErrorEventArgs("Failed receiving video frame from SRV-1."));
                    }
                }
            }

            stopWatch.Stop( );

            if (PlayingFinished != null)
            {
                PlayingFinished(this, BestCS.Video.ReasonToFinishPlaying.StoppedByUser);
            }
        }
예제 #41
0
        protected void ProcessRequest(Request request, IDownloader downloader)
        {
            Page page = null;

#if TEST
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
#endif

            try
            {
#if TEST
                sw.Reset();
                sw.Start();
#endif
                page = downloader.Download(request, this);

#if TEST
                sw.Stop();
                Console.WriteLine("Download:" + (sw.ElapsedMilliseconds).ToString());
#endif
                if (page.IsSkip)
                {
                    return;
                }

                if (PageHandlers != null)
                {
                    foreach (var pageHandler in PageHandlers)
                    {
                        pageHandler?.Invoke(page);
                    }
                }

#if TEST
                sw.Reset();
                sw.Start();
#endif
                PageProcessor.Process(page);
#if TEST
                sw.Stop();
                Console.WriteLine("Process:" + (sw.ElapsedMilliseconds).ToString());
#endif
            }
            catch (DownloadException de)
            {
                if (Site.CycleRetryTimes > 0)
                {
                    page = AddToCycleRetry(request, Site);
                }
                Logger.Warn(de.Message);
            }
            catch (Exception e)
            {
                if (Site.CycleRetryTimes > 0)
                {
                    page = AddToCycleRetry(request, Site);
                }
                Logger.Warn("解析页数数据失败: " + request.Url + ", 请检查您的数据抽取设置.");
            }

            //watch.Stop();
            //Logger.Info("dowloader cost time:" + watch.ElapsedMilliseconds);

            if (page == null)
            {
                OnError(request);
                return;
            }

            if (page.IsNeedCycleRetry)
            {
                ExtractAndAddRequests(page, true);
                return;
            }

            //watch.Stop();
            //Logger.Info("process cost time:" + watch.ElapsedMilliseconds);

            if (!page.MissTargetUrls)
            {
                if (!(SkipWhenResultIsEmpty && page.ResultItems.IsSkip))
                {
                    ExtractAndAddRequests(page, SpawnUrl);
                }
            }
#if TEST
            sw.Reset();
            sw.Start();
#endif
            if (!page.ResultItems.IsSkip)
            {
                foreach (IPipeline pipeline in Pipelines)
                {
                    pipeline.Process(page.ResultItems, this);
                }
            }
            else
            {
                var message = $"页面 {request.Url} 解析结果为 0.";
                Logger.Warn(message);
            }
            Logger.Info($"采集: {request.Url} 成功.");
#if TEST
            sw.Stop();
            Console.WriteLine("IPipeline:" + (sw.ElapsedMilliseconds).ToString());
#endif
        }
예제 #42
0
        async static Task CreateTableAndPopulate(Emojis emojisToLoad)
        {
            var table    = EmojiTable.Get();
            var imgTable = EmojiTable.GetImg();

            // Drop and recreate table
            await table.DeleteIfExistsAsync();

            await table.CreateIfNotExistsAsync();

            await imgTable.DeleteIfExistsAsync();

            await imgTable.CreateIfNotExistsAsync();

            //Entities
            var emojis = new List <EmojiEntity>();
            //Create the batch operation
            var batchOps    = new List <TableBatchOperation>();
            var imgBatchOps = new List <TableBatchOperation>();

            foreach (var g in emojisToLoad.Groups)
            {
                var batchOp    = new TableBatchOperation();
                var imgBatchOp = new TableBatchOperation();
                var groupId    = emojisToLoad.Groups.IndexOf(g).ToString(EmojiMetadata.IdFormat);

                foreach (var sg in g.SubGroups)
                {
                    foreach (var e in sg.Emojis)
                    {
                        var entity = new EmojiEntity(groupId, e.Id.ToString(EmojiMetadata.IdFormat))
                        {
                            Group    = g.Name,
                            SubGroup = sg.Name,
                            Code     = e.CodeString,
                            Emoji    = e.Emoji,
                            Cldr     = e.Cldr,
                            Keywords = e.Haystack,
                            IsNew    = e.IsNew
                        };
                        emojis.Add(entity);
                        batchOp.Insert(entity);

                        if (!string.IsNullOrWhiteSpace(e.ImageBase64))
                        {
                            var imgEntity = new EmojiImageEntity(groupId, e.Id.ToString(EmojiMetadata.IdFormat))
                            {
                                Emoji       = e.Emoji,
                                ImageBase64 = e.ImageBase64
                            };

                            imgBatchOp.Insert(imgEntity);
                        }

                        // Maximum operations in a batch
                        if (batchOp.Count == 100)
                        {
                            batchOps.Add(batchOp);
                            batchOp = new TableBatchOperation();

                            imgBatchOps.Add(imgBatchOp);
                            imgBatchOp = new TableBatchOperation();
                        }
                    }
                }

                // Batch can only contain operations in the same partition
                if (batchOp.Count > 0)
                {
                    batchOps.Add(batchOp);
                }
            }

            var sw             = new System.Diagnostics.Stopwatch();
            var processedCount = 0;

            foreach (var bo in batchOps)
            {
                sw.Reset();
                Console.WriteLine($"Inserting batch for group {bo.First().Entity.PartitionKey}, {bo.Count} entries");
                sw.Start();
                var result = await table.ExecuteBatchAsync(bo);

                processedCount += bo.Count;
                sw.Stop();
                Console.WriteLine($"  Insert complete: {sw.ElapsedMilliseconds}ms");
                Console.WriteLine($"  Processed: {processedCount} emojis");
            }

            processedCount = 0;
            Console.WriteLine($"###IMAGES###");
            foreach (var bo in imgBatchOps)
            {
                sw.Reset();
                Console.WriteLine($"Inserting image batch for group {bo.First().Entity.PartitionKey}, {bo.Count} entries");
                sw.Start();
                var result = await imgTable.ExecuteBatchAsync(bo);

                sw.Stop();
                processedCount += bo.Count;
                Console.WriteLine($"  Insert complete: {sw.ElapsedMilliseconds}ms");
                Console.WriteLine($"  Processed: {processedCount} emojis");
            }
        }
예제 #43
0
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            if (((MenuItem)sender).Uid == null)
            {
                return;
            }
            string clip = ClipBoardHelper.GetClipBoard_UnicodeText();

            if (!string.IsNullOrWhiteSpace((string)(((MenuItem)sender).ToolTip)))
            {
                clip = (string)(((MenuItem)sender).ToolTip);
            }
            StringBuilder sb = new StringBuilder();

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset();
            sw.Start();
            switch (((MenuItem)sender).Uid)
            {
            case "1":
                this.Visibility = this.Visibility == Visibility.Visible ? Visibility.Hidden : Visibility.Visible;
                break;

            case "a1":
                if (App.Settings.RecognitionEncoding)
                {
                    int encodingtype = EncodingAnalyzer.Analyze(clip);
                    if (encodingtype == 0 || encodingtype == 1)
                    {
                        if (MessageBox.Show(this, "編碼似乎已是Big5,繼續轉換?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        {
                            return;
                        }
                    }
                }
                clip = ConvertHelper.Convert(clip, new Encoding[] { Encoding.GetEncoding("GBK"), Encoding.GetEncoding("BIG5") }, 1);
                break;

            case "a2":
                if (App.Settings.RecognitionEncoding)
                {
                    int encodingtype = EncodingAnalyzer.Analyze(clip);
                    if (encodingtype == 2 || encodingtype == 3)
                    {
                        if (MessageBox.Show(this, "編碼似乎已是GBK,繼續轉換?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        {
                            return;
                        }
                    }
                }
                clip = ConvertHelper.Convert(clip, new Encoding[] { Encoding.GetEncoding("BIG5"), Encoding.GetEncoding("GBK") }, 2);
                break;

            case "a3":
                clip = ConvertHelper.Convert(clip, 1);
                break;

            case "a4":
                clip = ConvertHelper.Convert(clip, 2);
                break;

            case "b1":
                Window_DialogHost window_File_FileNameConverter = new Window_DialogHost(Enums.Enum_Mode.Mode.File_FileName);
                window_File_FileNameConverter.Show();
                break;

            case "b2":
                Window_DialogHost window_ClipBoard_Converter = new Window_DialogHost(Enums.Enum_Mode.Mode.ClipBoard);
                window_ClipBoard_Converter.Show();
                break;

            case "c1":
                Window_DialogHost Window_DialogHost = new Window_DialogHost(Enums.Enum_Mode.Mode.AutioTag, Format.ID3);
                Window_DialogHost.Show();
                break;

            case "c2":
                Window_DialogHost Window_DialogHost2 = new Window_DialogHost(Enums.Enum_Mode.Mode.AutioTag, Format.APE);
                Window_DialogHost2.Show();
                break;

            case "c3":
                Window_DialogHost Window_DialogHost3 = new Window_DialogHost(Enums.Enum_Mode.Mode.AutioTag, Format.OGG);
                Window_DialogHost3.Show();
                break;

            case "za1":
                foreach (char c in clip)
                {
                    if ((' ' <= c && c <= '~') || (c == '\r') || (c == '\n'))
                    {
                        if (c == '&')
                        {
                            sb.Append("&amp;");
                        }
                        else if (c == '<')
                        {
                            sb.Append("&lt;");
                        }
                        else if (c == '>')
                        {
                            sb.Append("&gt;");
                        }
                        else
                        {
                            sb.Append(c.ToString());
                        }
                    }
                    else
                    {
                        sb.Append("&#");
                        sb.Append(Convert.ToInt32(c));
                        sb.Append(";");
                    }
                }
                clip = sb.ToString();
                break;

            case "za2":
                foreach (char c in clip)
                {
                    if ((' ' <= c && c <= '~') || (c == '\r') || (c == '\n'))
                    {
                        if (c == '&')
                        {
                            sb.Append("&amp;");
                        }
                        else if (c == '<')
                        {
                            sb.Append("&lt;");
                        }
                        else if (c == '>')
                        {
                            sb.Append("&gt;");
                        }
                        else
                        {
                            sb.Append(c.ToString());
                        }
                    }
                    else
                    {
                        sb.Append("&#x");
                        sb.Append(Convert.ToInt32(c).ToString("X"));
                        sb.Append(";");
                    }
                }
                clip = sb.ToString();
                break;

            case "za3":
                clip.Replace("&amp;", "&");
                clip.Replace("&lt;", "<");
                clip.Replace("&gt;", ">");
                //以;將文字拆成陣列
                string[] tmp = clip.Split(';');
                //檢查最後一個字元是否為【;】,因為有【英文】、【阿拉伯數字】、【&#XXXX;】
                //若最後一個要處理的字並非HTML UNICODE則不進行處理
                bool Process_last = clip.Substring(clip.Length - 1, 1).Equals(";");
                //Debug.WriteLine(tmp.Length + "");
                for (int i = 0; i < tmp.Length; i++)
                {
                    //以&#將文字拆成陣列
                    string[] tmp2 = tmp[i].Split(new string[] { "&#" }, StringSplitOptions.RemoveEmptyEntries);
                    if (tmp2.Length == 1)
                    {
                        //如果長度為1則試圖轉換UNICODE回字符,若失敗則使用原本的字元
                        if (i != tmp.Length - 1)
                        {
                            try
                            {
                                if (tmp2[0].StartsWith("x"))
                                {
                                    sb.Append(Convert.ToChar(Convert.ToInt32(tmp2[0].Substring(1, tmp2[0].Length - 1), 16)).ToString());
                                }
                                else
                                {
                                    sb.Append(Convert.ToChar(Convert.ToInt32(int.Parse(tmp2[0]))).ToString());
                                }
                            }
                            catch
                            {
                                sb.Append(tmp2[0]);
                            }
                        }
                        else
                        {
                            sb.Append(tmp2[0]);
                        }
                    }
                    if (tmp2.Length == 2)
                    {
                        //若長度為2,則第一項不處理,只處理第二項即可
                        sb.Append(tmp2[0]);
                        var g = Convert.ToInt32(tmp2[1].Substring(1, tmp2[1].Length - 1), 16);
                        if (tmp2[1].StartsWith("x"))
                        {
                            sb.Append(Convert.ToChar(Convert.ToInt32(tmp2[1].Substring(1, tmp2[1].Length - 1), 16)).ToString());
                        }
                        else
                        {
                            sb.Append(Convert.ToChar(Convert.ToInt32(tmp2[1])).ToString());
                        }
                    }
                }
                clip = sb.ToString();
                break;

            case "zb1":
                //Unicode>GBK
                clip = Encoding.Default.GetString(Encoding.GetEncoding("GBK").GetBytes(clip));
                break;

            case "zb2":
                clip = Encoding.Default.GetString(Encoding.GetEncoding("BIG5").GetBytes(clip));
                break;

            case "zb3":
                clip = Encoding.Default.GetString(Encoding.GetEncoding("Shift-JIS").GetBytes(clip));
                break;

            case "zb4":
                //GBK>Unicode
                clip = Encoding.GetEncoding("GBK").GetString(Encoding.Default.GetBytes(clip));
                break;

            case "zb5":
                clip = Encoding.GetEncoding("BIG5").GetString(Encoding.Default.GetBytes(clip));
                break;

            case "zb6":
                clip = Encoding.GetEncoding("Shift-JIS").GetString(Encoding.Default.GetBytes(clip));
                break;

            case "zc1":
                //Shift-JIS>GBK
                clip = Encoding.GetEncoding("shift_jis").GetString(Encoding.GetEncoding("GBK").GetBytes(clip));
                break;

            case "zc2":
                clip = Encoding.GetEncoding("shift_jis").GetString(Encoding.GetEncoding("BIG5").GetBytes(clip));
                break;

            case "zc3":
                clip = Encoding.GetEncoding("GBK").GetString(Encoding.GetEncoding("shift_jis").GetBytes(clip));
                break;

            case "zc4":
                clip = Encoding.GetEncoding("BIG5").GetString(Encoding.GetEncoding("shift_jis").GetBytes(clip));
                break;

            case "zd1":
                //hz-gb-2312>GBK
                clip = Encoding.GetEncoding("hz-gb-2312").GetString(Encoding.GetEncoding("GBK").GetBytes(clip));
                break;

            case "zd2":
                clip = Encoding.GetEncoding("hz-gb-2312").GetString(Encoding.GetEncoding("BIG5").GetBytes(clip));
                break;

            case "zd3":
                clip = Encoding.GetEncoding("GBK").GetString(Encoding.GetEncoding("hz-gb-2312").GetBytes(clip));
                break;

            case "zd4":
                clip = Encoding.GetEncoding("BIG5").GetString(Encoding.GetEncoding("hz-gb-2312").GetBytes(clip));
                break;

            case "ze1":
                clip = Moudle.ConvertHelper.ConvertSymbol(clip, 0);
                break;

            case "ze2":
                clip = Moudle.ConvertHelper.ConvertSymbol(clip, 1);
                break;
            }
            ClipBoardHelper.SetClipBoard_UnicodeText(clip);
            sw.Stop();
            //顯示提示
            switch (((MenuItem)sender).Uid)
            {
            case "1":
            case "b1":
            case "b2":
            case "c1":
            case "c2":
            case "c3":
                break;

            default:
                if (App.Settings.Prompt && !(((MenuItem)sender).Visibility == Visibility.Hidden && (App.Settings.HotKey.AutoCopy || App.Settings.HotKey.AutoPaste)))
                {
                    ContextMenu NotifyIconMenu = (ContextMenu)this.FindResource("NotifyIconMenu");
                    string      ItemInfo       = ((MenuItem)GetByUid(NotifyIconMenu, ((MenuItem)sender).Uid)).Header.ToString();
                    new Toast(string.Format("轉換完成\r\n耗時:{0} ms", sw.ElapsedMilliseconds)).Show();
                }
                break;
            }
        }
        private void ProcessTouches()
        {
            CalculateFocus(CurrentTrackedTouches);

            if (!TrackedTouchCountIsWithinRange)
            {
                return;
            }

            float distance  = DistanceBetweenPoints(CurrentTrackedTouches[0].X, CurrentTrackedTouches[0].Y, CurrentTrackedTouches[1].X, CurrentTrackedTouches[1].Y);
            float distanceX = Distance(CurrentTrackedTouches[0].X - CurrentTrackedTouches[1].X);
            float distanceY = Distance(CurrentTrackedTouches[0].Y - CurrentTrackedTouches[1].Y);

            if (State == GestureRecognizerState.Possible)
            {
                if (previousDistance == 0.0f)
                {
                    // until the gesture starts, previousDistance is actually firstDistance
                    previousDistance  = distance;
                    previousDistanceX = distanceX;
                    previousDistanceY = distanceY;
                }
                else
                {
                    float diff = Math.Abs(previousDistance - distance);
                    if (diff >= ThresholdUnits)
                    {
                        SetState(GestureRecognizerState.Began);
                    }
                }
            }
            else if (State == GestureRecognizerState.Executing)
            {
                // must have a change in distance to execute
                if (distance != previousDistance)
                {
                    // line 3300: https://chromium.googlesource.com/chromiumos/platform/gestures/+/master/src/immediate_interpreter.cc

                    // get jitter threshold based on stationary movement or not
                    float jitterThreshold = (float)timer.Elapsed.TotalSeconds <= stationaryTimeSeconds ? minimumScaleResolutionSquared : stationaryScaleResolutionSquared;

                    // calculate distance suqared
                    float currentDistanceSquared  = distance * distance;
                    float previousDistanceSquared = previousDistance * previousDistance;

                    // if a change in direction, the jitter threshold can be increased to determine whether the change in direction is significant enough
                    if ((currentDistanceSquared - previousDistanceSquared) * previousDistanceDirection < 0.0f)
                    {
                        jitterThreshold = Math.Max(jitterThreshold, hysteresisScaleResolutionSquared);
                    }

                    // check if we are above the jitter threshold - will always be true if moving in the same direction as last time
                    bool aboveJitterThreshold = ((previousDistanceSquared > jitterThreshold * currentDistanceSquared) ||
                                                 (currentDistanceSquared > jitterThreshold * previousDistanceSquared));

                    // must be above jitter threshold to execute
                    if (aboveJitterThreshold)
                    {
                        timer.Reset();
                        timer.Start();
                        float newDistanceDirection = (currentDistanceSquared - previousDistanceSquared >= 0.0f ? 1.0f : -1.0f);
                        if (newDistanceDirection == previousDistanceDirection)
                        {
                            ScaleMultiplier  = GetScale(distance / previousDistance);
                            ScaleMultiplierX = GetScale(distanceX / previousDistanceX);
                            ScaleMultiplierY = GetScale(distanceY / previousDistanceY);
                            SetState(GestureRecognizerState.Executing);
                        }
                        else
                        {
                            ScaleMultiplier           = ScaleMultiplierX = ScaleMultiplierY = 1.0f;
                            previousDistanceDirection = newDistanceDirection;
                        }
                        SetPreviousDistance(distance, distanceX, distanceY);
                    }
                    else if (timer.ElapsedMilliseconds > resetDirectionMilliseconds)
                    {
                        previousDistanceDirection = 0.0f;
                    }
                }
            }
            else if (State == GestureRecognizerState.Began)
            {
                ScaleMultiplier           = ScaleMultiplierX = ScaleMultiplierY = 1.0f;
                previousDistanceDirection = 0.0f;
                SetPreviousDistance(distance, distanceX, distanceY);
                SetState(GestureRecognizerState.Executing);
            }
            else
            {
                SetState(GestureRecognizerState.Possible);
            }
        }
        /// <summary>
        /// get from cache or create a new one
        /// </summary>
        /// <param name="reqFont"></param>
        /// <returns></returns>
        public SimpleFontAtlas GetFontAtlas(RequestFont reqFont, out GLBitmap glBmp)
        {
#if DEBUG
            _dbugStopWatch.Reset();
            _dbugStopWatch.Start();
#endif

            int             fontKey = reqFont.FontKey;
            SimpleFontAtlas fontAtlas;
            if (!_createdAtlases.TryGetValue(fontKey, out fontAtlas))
            {
                //check from pre-built cache (if availiable)
                Typeface resolvedTypeface = textServices.ResolveTypeface(reqFont);

                string fontTextureFile     = reqFont.Name + " " + fontKey;
                string resolveFontFile     = fontTextureFile + ".info";
                string fontTextureInfoFile = resolveFontFile;
                string fontTextureImg      = fontTextureInfoFile + ".png";

                if (StorageService.Provider.DataExists(fontTextureInfoFile))
                {
                    SimpleFontAtlasBuilder atlasBuilder2 = new SimpleFontAtlasBuilder();

                    using (System.IO.Stream dataStream = StorageService.Provider.ReadDataStream(fontTextureInfoFile))
                    {
                        try
                        {
                            fontAtlas                     = atlasBuilder2.LoadAtlasInfo(dataStream);
                            fontAtlas.TotalGlyph          = ReadGlyphImages(fontTextureImg);
                            fontAtlas.OriginalFontSizePts = reqFont.SizeInPoints;
                            _createdAtlases.Add(fontKey, fontAtlas);
                            //
                            //calculate some commonly used values
                            fontAtlas.SetTextureScaleInfo(
                                resolvedTypeface.CalculateScaleToPixelFromPointSize(fontAtlas.OriginalFontSizePts),
                                resolvedTypeface.CalculateScaleToPixelFromPointSize(reqFont.SizeInPoints));
                            //TODO: review here, use scaled or unscaled values
                            fontAtlas.SetCommonFontMetricValues(
                                resolvedTypeface.Ascender,
                                resolvedTypeface.Descender,
                                resolvedTypeface.LineGap,
                                resolvedTypeface.CalculateRecommendLineSpacing());
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
                else
                {
                    GlyphImage             totalGlyphsImg = null;
                    SimpleFontAtlasBuilder atlasBuilder   = null;
                    var textureGen = new GlyphTextureBitmapGenerator();
                    textureGen.CreateTextureFontFromScriptLangs(
                        resolvedTypeface,
                        reqFont.SizeInPoints,
                        _textureKind,
                        _textureBuildDetails,
                        (glyphIndex, glyphImage, outputAtlasBuilder) =>
                    {
                        if (outputAtlasBuilder != null)
                        {
                            //finish
                            atlasBuilder = outputAtlasBuilder;
                        }
                    }
                        );

                    //
                    totalGlyphsImg = atlasBuilder.BuildSingleImage();
                    //if (reqFont.SizeInPoints == 14 && cacheImg != null)
                    //{
                    //    totalGlyphsImg = cacheImg;
                    //}
                    //totalGlyphsImg = Sharpen(totalGlyphsImg, 1); //test shapen primary image
                    //-
                    //
                    //create atlas
                    fontAtlas            = atlasBuilder.CreateSimpleFontAtlas();
                    fontAtlas.TotalGlyph = totalGlyphsImg;
#if DEBUG
                    //save glyph image for debug
                    //PixelFarm.Agg.ActualImage.SaveImgBufferToPngFile(
                    //    totalGlyphsImg.GetImageBuffer(),
                    //    totalGlyphsImg.Width * 4,
                    //    totalGlyphsImg.Width, totalGlyphsImg.Height,
                    //    "d:\\WImageTest\\total_" + reqFont.Name + "_" + reqFont.SizeInPoints + ".png");
                    ////save image to cache
                    SaveImgBufferToFile(totalGlyphsImg, fontTextureImg);
#endif

                    //cache the atlas
                    _createdAtlases.Add(fontKey, fontAtlas);
                    //
                    //calculate some commonly used values
                    fontAtlas.SetTextureScaleInfo(
                        resolvedTypeface.CalculateScaleToPixelFromPointSize(fontAtlas.OriginalFontSizePts),
                        resolvedTypeface.CalculateScaleToPixelFromPointSize(reqFont.SizeInPoints));
                    //TODO: review here, use scaled or unscaled values
                    fontAtlas.SetCommonFontMetricValues(
                        resolvedTypeface.Ascender,
                        resolvedTypeface.Descender,
                        resolvedTypeface.LineGap,
                        resolvedTypeface.CalculateRecommendLineSpacing());

                    ///
#if DEBUG
                    _dbugStopWatch.Stop();
                    System.Diagnostics.Debug.WriteLine("build font atlas: " + _dbugStopWatch.ElapsedMilliseconds + " ms");
#endif

                    //save font info to cache
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        atlasBuilder.SaveAtlasInfo(ms);
                        StorageService.Provider.SaveData(fontTextureInfoFile, ms.ToArray());
                    }
                }
            }

            glBmp = _loadedGlyphs.GetOrCreateNewOne(fontAtlas);
            return(fontAtlas);
        }
예제 #46
0
        private static IEnumerator FindIllegalShadersEnumerator(GameObject target, string[] whitelist, System.Action <Shader> onFound, bool useWatch = false)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            if (useWatch)
            {
                watch.Start();
            }

            List <Material>    materialCache = new List <Material>();
            Queue <GameObject> children      = new Queue <GameObject>();

            children.Enqueue(target.gameObject);
            while (children.Count > 0)
            {
                GameObject child = children.Dequeue();
                if (child == null)
                {
                    continue;
                }

                for (int idx = 0; idx < child.transform.childCount; ++idx)
                {
                    children.Enqueue(child.transform.GetChild(idx).gameObject);
                }

                foreach (Renderer childRenderers in child.transform.GetComponents <Renderer>())
                {
                    if (childRenderers == null)
                    {
                        continue;
                    }

                    foreach (Material sharedMaterial in childRenderers.sharedMaterials)
                    {
                        if (materialCache.Any(cacheMtl => sharedMaterial == cacheMtl)) // did we already look at this one?
                        {
                            continue;
                        }

                        // Skip empty material slots, or materials without shaders.
                        // Both will end up using the magenta error shader.
                        if (sharedMaterial == null || sharedMaterial.shader == null)
                        {
                            continue;
                        }

                        if (whitelist.All(okayShaderName => sharedMaterial.shader.name != okayShaderName))
                        {
                            onFound(sharedMaterial.shader);
                            yield return(null);
                        }

                        materialCache.Add(sharedMaterial);
                    }

                    if (!useWatch || watch.ElapsedMilliseconds <= 1)
                    {
                        continue;
                    }

                    yield return(null);

                    watch.Reset();
                }
            }
        }
예제 #47
0
 public void StartUpdateTimer()
 {
     timer.Reset();
     timer.Start();
 }
예제 #48
0
/**
 * Stupidly, Unity in 2D mode uses co-ords incompatible with Unity in 3D mode (xy instead of xz).
 *
 * So we have to provide a boolean to switch between the two modes!
 */
        public static VoronoiDiagram CreateDiagramFromVoronoiOutput(Voronoi voronoiGenerator, bool useUnity2DCoordsNot3D)
        {
            GameObject go           = new GameObject("New VoronoiMap");
            GameObject goCellHolder = new GameObject(_cellHolderName);

            goCellHolder.transform.parent = go.transform;
            GameObject goEdgeHolder = new GameObject(_edgeHolderName);

            goEdgeHolder.transform.parent = go.transform;
            GameObject goVertexHolder = new GameObject(_vertexHolderName);

            goVertexHolder.transform.parent = go.transform;

            VoronoiDiagram map = go.AddComponent <VoronoiDiagram>();

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Reset();
            watch.Start();

            Dictionary <Site, VoronoiCell>          generatedCells    = new Dictionary <Site, VoronoiCell>();
            Dictionary <Vector2, VoronoiCellVertex> generatedVertices = new Dictionary <Vector2, VoronoiCellVertex>();

            int numEdgesCreated = 0;

            foreach (Edge edge in voronoiGenerator.Edges())
            {
                GameObject goEdge = new GameObject("Edge-#" + (numEdgesCreated++));
                goEdge.transform.parent = goEdgeHolder.transform;

                VoronoiCellEdge vEdge = goEdge.AddComponent <VoronoiCellEdge>();
                Debug.Log("Processing edge = " + edge + " with clippedEnds = " + (edge.clippedEnds == null?"null":"" + edge.clippedEnds.Count));
                if (!edge.visible)
                {
                    Debug.Log("...Voronoi algorithm generated a non-existent edge, skipping it...");
                    continue;
                }
                Vector2 clippedEndLeft  = (Vector2)edge.clippedEnds [Side.LEFT];
                Vector2 clippedEndRight = (Vector2)edge.clippedEnds [Side.RIGHT];
                vEdge.AddVertex(FetchVertexOrAddToObject(clippedEndLeft, generatedVertices, goVertexHolder, useUnity2DCoordsNot3D));
                vEdge.AddVertex(FetchVertexOrAddToObject(clippedEndRight, generatedVertices, goVertexHolder, useUnity2DCoordsNot3D));
                goEdge.transform.localPosition = (vEdge.edgeVertexA.transform.localPosition + vEdge.edgeVertexB.transform.localPosition) / 2.0f;

                Site[] bothSites = new Site[] { edge.leftSite, edge.rightSite };
                foreach (Site site in bothSites)
                {
                    /** Re-use or create the Cell */
                    VoronoiCell newCell = null; // C# is rubbish. Crashes if Dictionary lacks the key. Very bad design.
                    if (generatedCells.ContainsKey(site))
                    {
                        newCell = generatedCells [site];
                    }
                    GameObject goCell;

                    if (newCell == null)
                    {
                        goCell = new GameObject("Cell-#" + generatedCells.Count);
                        goCell.transform.parent        = goCellHolder.transform;
                        goCell.transform.localPosition = new Vector3(site.Coord.x, useUnity2DCoordsNot3D? site.Coord.y : 0, useUnity2DCoordsNot3D? 0 : site.Coord.y);
                        newCell = goCell.AddComponent <VoronoiCell>();
                        generatedCells.Add(site, newCell);
                    }
                    else
                    {
                        goCell = newCell.gameObject;
                    }

                    /** Now that cell is created, attach it to BOTH Vertex's on the new Edge
                     *        (so that later its easy for us to to find Cells-for-this-Vertex, and also:
                     *        for a Cell to "trace" around its edges, picking "next edge" from each Vertex
                     *        by looking at which edges from the vertex border this cell (by checking
                     *        that BOTH Vertex-ends of the edge are attached to this cell)
                     *
                     *        Also add the edge itself to the cell, and the cell to the edge.
                     */
                    vEdge.AddCellWithSideEffects(newCell);
                }
            }
            watch.Stop();

            return(map);
        }
        private void Run()
        {
            outputWriter = new StreamWriter(outputFilePath, false);
            try
            {
                startTime.ToString().Dump("Started At");



                int batchNumber  = 0;
                var sourceLength = GetTotalRecordsCount(sourceFilePath);
                sourceLength.Dump("Source File Records Count");
                var targetLength = GetTotalRecordsCount(targetFilePath);
                targetLength.Dump("Target File Records Count");
                int totalBatchesToRun = sourceLength / batch_size;

                Console.WriteLine("Total Records diff by length {0}", (sourceLength - targetLength));

                Console.WriteLine("Total batch to run.{0}", totalBatchesToRun);



                int index = 0;
                //totalBatchesToRun =1;
                for (int i = 0; i < totalBatchesToRun; i++)
                {
                    sw.Start();

                    var sourceRecords = GetRecords(sourceFilePath, batchNumber, batch_size);
                    var targetRecords = GetRecords(targetFilePath, batchNumber, batch_size);

                    var rs = from s in sourceRecords
                             join t in targetRecords
                             on s.Key equals t.Key
                             where s.Value != t.Value
                             select new
                    {
                        SourceKey  = s.Key,
                        TargetKey  = t.Key,
                        SourceHash = s.Value,
                        TargetHash = t.Value,
                    };

                    results.AddRange(rs);
                    sw.Stop();
                    long batchTimeTook = sw.ElapsedMilliseconds;
                    totalMS += batchTimeTook;
                    ("Starting batch code :" + i + " / " + totalBatchesToRun + "  batch starting at " + batchNumber + " in " + sw.ElapsedMilliseconds + " ms").Dump("");
                    sw.Reset();
                    batchNumber += batch_size;
                }
            }
            finally
            {
                //rs.Dump("Diff records in Batch:" + batchNumber);
                foreach (var r in results)
                {
                    //r.Dump("Record");
                    lock (locker)
                    {
                        outputWriter.WriteLine(r);
                    }
                }

                var diffrecords = System.IO.File.ReadLines(outputFilePath).Count();
                Console.WriteLine("Diff records :{0}", diffrecords);
                outputWriter.Close();
                outputWriter.Dispose();

                Console.WriteLine("Time Taken {0}ms", totalMS);
            }
        }
예제 #50
0
        private void refresh_Tick(object sender, EventArgs e)
        {
            if (Car.Round == Menue.Anz_rounds)
            {
                if (Car.Compare_to_player == 1)
                {
                    Menue.Times_player_1 = Car.Round_time;
                }
                else if (Car.Compare_to_player == 2)
                {
                    Menue.Times_player_2 = Car.Round_time;
                }
                round_timer.Stop();

                if (Menue.End_the_game == false)
                {
                    Menue.End_the_game = true;
                    Menue.Time_list_after_game();
                }
                wait_for_end_game();

                Car.Round++;
            }
            else if (Start.Ready)
            {
                round_timer.Start();
            }

            if (Car.Round < Menue.Anz_rounds)
            {
                Rounds.Text = "Spieler " + Car.Compare_to_player.ToString() + "\n" + (Car.Round + 1).ToString() + "/" + Menue.Anz_rounds.ToString();
            }
            else
            {
                Rounds.Text = "Spieler " + Car.Compare_to_player.ToString() + "\nim Ziel";
            }


            //Check if the car is on the Road
            if (Map.car_on_road(Car.Position_x, Car.Position_y, Grid, Car.Rotation) == true)
            {
                Car.ON_ROAD = true;
            }
            else
            {
                Car.ON_ROAD = false;
            }

            if (Map.car_over_checkpoint(Car.Position_x, Car.Position_y, Grid, Car.Rotation))
            {
                if ((Car.On_checkpoint == false))
                {
                    Car.checked_checkpoint(Car.Position_x, Car.Position_y, Grid);
                    Car.On_checkpoint = true;
                }
            }
            else
            {
                Car.On_checkpoint = false;
            }

            if ((Map.car_over_finish(Car.Position_x, Car.Position_y, Grid, Car.Rotation)) && (Car.all_checkpoints() == true))
            {
                if ((Car.On_finish == false))
                {
                    Car.Round_time[Convert.ToInt16(Car.Round)] = round_timer.ElapsedMilliseconds;

                    if (Car.Compare_to_player == 1)
                    {
                        Menue.Times_player_1[Convert.ToInt16(Car.Round)] = Car.Round_time[Convert.ToInt16(Car.Round)];
                    }
                    else if (Car.Compare_to_player == 2)
                    {
                        Menue.Times_player_2[Convert.ToInt16(Car.Round)] = Car.Round_time[Convert.ToInt16(Car.Round)];
                    }

                    Car.Round++;
                    Car.On_finish = true;
                    Car.clear_checkpoint();
                }
            }
            else
            {
                Car.On_finish = false;
            }

            if (Start.In_start_sequenze)
            {
                round_timer.Reset();
            }
        }
예제 #51
0
        public void Mark(Marker marker, Order order)
        {
            _stopwatch.Stop();
            var ticks = _stopwatch.ElapsedTicks;

            _stopwatch.Reset();
            _stopwatch.Start();

            if (_start == false)
            {
                // Start profiling after first WaitForEndOfFrame=>FixedUpdate
                if (_lastMarker == Marker.WaitForEndOfFrame && marker == Marker.FixedUpdate)
                {
                    _start = true;
                }
                else
                {
                    _lastMarker = marker;
                    return;
                }
            }

            switch (marker)
            {
            case Marker.FixedUpdate:
                if (_lastMarker == Marker.WaitForFixedUpdate)
                {
                    _cur.WaitForFixedUpdate += ticks;
                    _cur.FixedUpdateCount++;
                }
                else if (_lastMarker == Marker.FixedUpdate)
                {
                    _cur.FixedUpdate += ticks;
                }
                else if (_lastMarker == Marker.WaitForEndOfFrame)
                {
                    _cur.FrameEnd = ticks;
                    Finish();
                    _cur.FixedUpdateCount++;
                }
                else
                {
                    //Debug.LogErrorFormat ("Internal error {0} => {1}", _lastMarker, marker);
                    _cur.Reset();
                }
                break;

            case Marker.WaitForFixedUpdate:
                if (_lastMarker == Marker.WaitForFixedUpdate)
                {
                    _cur.WaitForFixedUpdate += ticks;
                }
                else if (_lastMarker == Marker.FixedUpdate)
                {
                    _cur.Physics += ticks;
                }
                else
                {
                    Debug.LogErrorFormat("Internal error {0} => {1}", _lastMarker, marker);
                    _cur.Reset();
                }
                break;

            case Marker.Update:
                if (_lastMarker == Marker.Update)
                {
                    _cur.Update += ticks;
                }
                else if (_lastMarker == Marker.WaitForEndOfFrame)
                {
                    // skipped FixedUpdate()
                    _cur.FrameEnd = ticks;
                    Finish();
                }
                else if (_lastMarker == Marker.WaitForFixedUpdate)
                {
                    // OnMouse...
                    // TODO: ticks to something
                }
                else
                {
                    //Debug.LogErrorFormat ("Internal error {0} => {1}", _lastMarker, marker);
                    Reset();
                }
                break;

            case Marker.LateUpdate:
                if (_lastMarker == Marker.LateUpdate)
                {
                    _cur.LateUpdate += ticks;
                }
                else if (_lastMarker == Marker.Update)
                {
                    _cur.YieldAndAnimation = ticks;
                }
                else
                {
                    //Debug.LogErrorFormat ("Internal error {0} => {1}", _lastMarker, marker);
                    Reset();
                }
                break;

            case Marker.WaitForEndOfFrame:
                if (_lastMarker == Marker.WaitForEndOfFrame)
                {
                    _cur.WaitForEndOfFrame += ticks;
                }
                else if (_lastMarker == Marker.LateUpdate)
                {
                    _cur.Render = ticks;
                }
                else
                {
                    //Debug.LogErrorFormat ("Internal error {0} => {1}", _lastMarker, marker);
                    Reset();
                }
                break;
            }
            //Debug.LogFormat ("{0} {1}", marker, order);

            _lastMarker = marker;
        }
예제 #52
0
        private void downloadFile(Int32 fileNr)
        {
            m_currentFileSize = 0;
            fireEventFromBgw(Event.FileDownloadAttempting);

            FileInfo file = this.Files[fileNr];
            Int64    size = 0;

            Byte[] readBytes = new Byte[this.PackageSize];
            Int32  currentPackageSize;

            System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch();
            Int32     readings = 0;
            Exception exc      = null;

            FileStream writer = new FileStream(this.LocalDirectory + "\\" + file.Name, System.IO.FileMode.Create);

            HttpWebRequest  webReq;
            HttpWebResponse webResp = null;

            try
            {
                webReq  = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path);
                webResp = (HttpWebResponse)webReq.GetResponse();

                size = webResp.ContentLength;
            }
            catch (Exception ex) { exc = ex; }

            m_currentFileSize = size;
            fireEventFromBgw(Event.FileDownloadStarted);

            if (exc != null)
            {
                bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc);
            }
            else
            {
                m_currentFileProgress = 0;
                while (m_currentFileProgress < size && !bgwDownloader.CancellationPending)
                {
                    while (this.IsPaused)
                    {
                        System.Threading.Thread.Sleep(100);
                    }

                    speedTimer.Start();

                    currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize);

                    m_currentFileProgress += currentPackageSize;
                    m_totalProgress       += currentPackageSize;
                    fireEventFromBgw(Event.ProgressChanged);

                    writer.Write(readBytes, 0, currentPackageSize);
                    readings += 1;

                    if (readings >= this.StopWatchCyclesAmount)
                    {
                        m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000 / (speedTimer.ElapsedMilliseconds + 1));
                        speedTimer.Reset();
                        readings = 0;
                    }
                }

                speedTimer.Stop();
                writer.Close();
                webResp.Close();
                if (!bgwDownloader.CancellationPending)
                {
                    fireEventFromBgw(Event.FileDownloadSucceeded);
                }
            }
            fireEventFromBgw(Event.FileDownloadStopped);
        }
예제 #53
0
        public void TestWarpedLineSymbolizer()
        {
            var p = new SharpMap.Data.Providers.ShapeFile(TestUtility.GetPathToTestFile("roads_aur.shp"), false);

            var l = new SharpMap.Layers.VectorLayer("roads", p);

            var cls = new SharpMap.Rendering.Symbolizer.CachedLineSymbolizer();

            cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.PlainLineSymbolizeHandler
            {
                Line = new System.Drawing.Pen(System.Drawing.Color.Gold, 2)
            });

            var wls = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
            {
                Pattern =
                    SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.
                    GetGreaterSeries(3, 3),
                Line       = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1)
                , Interval = 20
            };

            cls.LineSymbolizeHandlers.Add(wls);
            l.Style.LineSymbolizer = cls;

            var m = new SharpMap.Map(new System.Drawing.Size(720, 540))
            {
                BackColor = System.Drawing.Color.Cornsilk
            };

            m.Layers.Add(l);

            m.ZoomToExtents();

            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            var bmp = m.GetMap();

            sw.Stop();
            System.Diagnostics.Trace.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save(System.IO.Path.Combine(UnitTestsFixture.GetImageDirectory(this), "AurichRoads1.bmp"));

            cls.LineSymbolizeHandlers[1] = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
            {
                Pattern =
                    SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.
                    GetTriangle(4, 0),
                Line       = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1),
                Fill       = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
                , Interval = 10
            };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            System.Diagnostics.Trace.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save(System.IO.Path.Combine(UnitTestsFixture.GetImageDirectory(this), "AurichRoads2-0.bmp"));

            cls.LineSymbolizeHandlers[1] = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
            {
                Pattern =
                    SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.
                    GetTriangle(4, 1),
                Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1),
                Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
                ,
                Interval = 10
            };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            System.Diagnostics.Trace.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save(System.IO.Path.Combine(UnitTestsFixture.GetImageDirectory(this), "AurichRoads2-1.bmp"));
            cls.LineSymbolizeHandlers[1] = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
            {
                Pattern =
                    SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.
                    GetTriangle(4, 2),
                Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1),
                Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
                ,
                Interval = 10
            };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            System.Diagnostics.Trace.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save(System.IO.Path.Combine(UnitTestsFixture.GetImageDirectory(this), "AurichRoads2-2.bmp"));

            cls.LineSymbolizeHandlers[1] = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
            {
                Pattern =
                    SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.
                    GetTriangle(4, 3),
                Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1),
                Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
                ,
                Interval = 10
            };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            System.Diagnostics.Trace.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save(System.IO.Path.Combine(UnitTestsFixture.GetImageDirectory(this), "AurichRoads2-3.bmp"));


            //cls.LineSymbolizeHandlers[0] = cls.LineSymbolizeHandlers[1];
            cls.LineSymbolizeHandlers[1] = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
            {
                Pattern =
                    SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.GetZigZag(4, 4),
                Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1),
                //Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
            };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            System.Diagnostics.Trace.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save(System.IO.Path.Combine(UnitTestsFixture.GetImageDirectory(this), "AurichRoads3.bmp"));
        }
예제 #54
0
파일: Program.cs 프로젝트: ivanhou/PInvoke
        static void Main(string[] args)
        {
            int result1 = CPlusPlusLib.Add(1, 2);
            int result2 = CPlusPlusLib.Sub(1, 2);
            int result3 = CPlusPlusLib.Multiply(2, 2);

            Console.WriteLine(string.Format("{0} {1} {2}", result1, result2, result3));

            /////////////////////////////////////////////////////////////////////
            CPlusPlusLib.PrintMsg("\nTest CPlusPlusLib");

            string        rawString      = "12345";
            StringBuilder reversedString = new StringBuilder(rawString.Length);

            CPlusPlusLib.ReverseAnsiString(rawString, reversedString);
            Console.WriteLine(string.Format("{0} , {1}", rawString, reversedString.ToString()));

            rawString = "123456";
            string reversedStringA;

            CPlusPlusLib.ReverseStringA(rawString, out reversedStringA);
            Console.WriteLine(string.Format("{0} , {1}", rawString, reversedStringA));

            string strNew = CPlusPlusLib.GetStringNew();

            Console.WriteLine(strNew);

            IntPtr stringPtr = CPlusPlusLib.GetStringNewA();
            string strNewA   = System.Runtime.InteropServices.Marshal.PtrToStringUni(stringPtr);

            Console.WriteLine(strNewA);

            ///////////////////////////////////////////////////////////////////
            System.Diagnostics.Stopwatch mWatch = new System.Diagnostics.Stopwatch();
            const int testCycle = 600000;

            mWatch.Reset();
            mWatch.Start();
            for (int i = 0; i < testCycle; i++)
            {
                CPlusPlusLib.IsAsciiNonblittable('a');
            }
            mWatch.Stop();
            Console.WriteLine("\ntime elapsed {0}", mWatch.ElapsedTicks);

            byte mb = (byte)'a';

            mWatch.Reset();
            mWatch.Start();
            for (int i = 0; i < testCycle; i++)
            {
                CPlusPlusLib.IsAsciiBlittable(mb);
            }
            mWatch.Stop();
            Console.WriteLine("time elapsed {0}", mWatch.ElapsedTicks);

            mWatch.Reset();
            mWatch.Start();
            for (int i = 0; i < testCycle; i++)
            {
                CPlusPlusLib.IsWasciiNonblittable('a');
            }
            mWatch.Stop();
            Console.WriteLine("time elapsed {0}", mWatch.ElapsedTicks);

            //////////////////////////////////////////////////////////////////
            IntPtr pString = IntPtr.Zero;
            IntPtr result  = IntPtr.Zero;

            result = CPlusPlusLib.BSTRString(out pString);

            if (IntPtr.Zero != pString)
            {
                string argString = Marshal.PtrToStringBSTR(pString);
                Console.WriteLine("\nargument out BSTR:{0}", argString);
                // Free BSTR
                Marshal.FreeBSTR(pString);
            }

            if (IntPtr.Zero != result)
            {
                string retString = Marshal.PtrToStringBSTR(result);
                Console.WriteLine("function return BSTR:{0}", retString);
                // Free BSTR
                Marshal.FreeBSTR(result);
            }

            ///////////////////////////////////////////////////////////////////
            StructArgument();
            StructReturn();

            //////////////////////////////////////////////////////
            StructAllocString();
            StructAllocString_IntPtrString();
            ClassNonBlittlable();

            ////////////////////////////////////////////////////
            StructAsRefField();
            StructAsValField();
            StructAsValFieldFlattened();

            ///////////////////////////////////////////////////
            CharArray();
            StringArray();


            CPlusPlusLib.CBFunction cb = new CPlusPlusLib.CBFunction(callback);
            CPlusPlusLib.CallResulOfFunction(2, 6, cb);

            CPlusPlusLib.CBFunction_A cb_A     = new CPlusPlusLib.CBFunction_A(callback_A);
            MsEmployee_Class          employee = new MsEmployee_Class();

            employee.EmployeeID = 10002;
            CPlusPlusLib.CallResulOfFunction_A(employee, cb_A);

            Console.WriteLine("\r\nPress any key to exit...");
            Console.Read();
        }
예제 #55
0
        public async Task <TotalMeasurementResult> Measure(int sampleSize, int minNumberOfDataPoints, int maxNumberOfDataPoints, int stepSize, bool applyCompression, string compressionType)
        {
            double transferTime        = 0;
            double deserializationTime = 0;
            string contentEncoding     = "";
            Stream responseStream      = null;
            double fileSize            = 0;

            TotalMeasurementResult totalMeasurementResult = new TotalMeasurementResult();

            for (var i = minNumberOfDataPoints; i <= maxNumberOfDataPoints; i += stepSize)
            {
                MeasurementResult measurementResult = new MeasurementResult();

                for (int j = 0; j < sampleSize; j++)
                {
                    //Streaming
                    System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                    stopwatch.Start();
                    HttpResponseMessage responseMessage = await base.MakeRequestAsync(i, applyCompression, compressionType);

                    contentEncoding = responseMessage.Content.Headers.ContentEncoding.ToString();
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        var packet = await responseMessage.Content.ReadAsStreamAsync();

                        stopwatch.Stop();
                        transferTime += stopwatch.ElapsedMilliseconds;
                        stopwatch.Reset();

                        fileSize += packet.Length;

                        stopwatch.Start();
                        //Decompression if compressed
                        //Deserialization
                        if (contentEncoding.ToLower().Contains("gzip"))
                        {
                            responseStream = new GZipStream(packet, CompressionMode.Decompress);
                        }
                        else if (contentEncoding.ToLower().Contains("deflate"))
                        {
                            responseStream = new DeflateStream(packet, CompressionMode.Decompress);
                        }
                        else if (contentEncoding.ToLower().Contains("br"))
                        {
                            responseStream = new BrotliStream(packet, CompressionMode.Decompress);
                        }
                        else
                        {
                            responseStream = packet;
                        }
                        MemoryStream ms = new MemoryStream();
                        responseStream.CopyTo(ms);
                        TimeSeriesData[] timeSeries = ZeroFormatterSerializer.Deserialize <TimeSeriesData[]>(ms.ToArray());
                        stopwatch.Stop();
                        deserializationTime += stopwatch.ElapsedMilliseconds;
                        stopwatch.Reset();
                    }
                }

                measurementResult.DataPoints = i;
                measurementResult.TransferAndSerializationTime = transferTime / sampleSize;
                measurementResult.DeserializationTime          = deserializationTime / sampleSize;
                measurementResult.FileSize = fileSize / sampleSize;
                totalMeasurementResult.ResultList.Add(measurementResult);
            }

            return(totalMeasurementResult);
        }
예제 #56
0
        void Update()
        {
            if (_KinectSensor.RawDepthImage != null)
            {
                // Visualize original depth image
                short[] depthImage = _KinectSensor.RawDepthImage;
                Buffer.BlockCopy(depthImage, 0, _DepthRawData, 0, _DepthRawData.Length * sizeof(byte));
                _DepthImageTexture.LoadRawTextureData(_DepthRawData);
                _DepthImageTexture.Apply();

                bool keyFrame = (_FrameCount++ % _KeyFrameInterval == 0);

                _Stopwatch.Reset();
                _Stopwatch.Start();

                // Temporal RVL compression
                _EncodedDepthData = _TrvlEncoder.Encode(depthImage, keyFrame);

                _Stopwatch.Stop();
                long encodingTimeMillseconds = _Stopwatch.ElapsedMilliseconds;

                _Stopwatch.Reset();
                _Stopwatch.Start();

                // Temporal RVL decompression
                _DecodedDepthData = _TrvlDecoder.Decode(_EncodedDepthData, keyFrame);

                _Stopwatch.Stop();
                long decodingTimeMillseconds = _Stopwatch.ElapsedMilliseconds;

                // Visualize decoded depth image
                Buffer.BlockCopy(_DecodedDepthData, 0, _DepthRawData, 0, _DepthRawData.Length * sizeof(byte));
                _DecodedDepthImageTexture.LoadRawTextureData(_DepthRawData);
                _DecodedDepthImageTexture.Apply();

                // Difference of depth images
                for (int i = 0; i < depthImage.Length; i++)
                {
                    _Diff[i] = (short)Math.Abs(depthImage[i] - _DecodedDepthData[i]);
                }

                // Visualize diff image
                Buffer.BlockCopy(_Diff, 0, _DepthRawData, 0, _DepthRawData.Length * sizeof(byte));
                _DiffImageTexture.LoadRawTextureData(_DepthRawData);
                _DiffImageTexture.Apply();

                // Display info
                int   originalDepthDataSize   = depthImage.Length * sizeof(short);
                int   compressedDepthDataSize = _EncodedDepthData.Length;
                float compressionRatio        = originalDepthDataSize / compressedDepthDataSize;

                _DepthImageSize.text = string.Format("Size: {2:#,0} [bytes]  Resolution: {0}x{1}",
                                                     _DepthImageTexture.width, _DepthImageTexture.height, originalDepthDataSize);
                _CompressedDepthImageSize.text = string.Format("Size: {0:#,0} [bytes]  Data compression ratio: {1:F1}",
                                                               compressedDepthDataSize, compressionRatio);
                _ProcessingTime.text = string.Format("Processing time:\n Encode: {0} [ms]\n Decode: {1} [ms]",
                                                     encodingTimeMillseconds, decodingTimeMillseconds);
            }

            if (_KinectSensor.RawColorImage != null)
            {
                _ColorImageTexture.LoadRawTextureData(_KinectSensor.RawColorImage);
                _ColorImageTexture.Apply();
            }
        }
예제 #57
0
        public void FilteringEfficiency()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;

            Utils.ShowStarting(methodName);

            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            const string rawFilePath = @"C:\cygwin\home\kims336\Data\TopDown\raw\SBEP_STM_001_02272012_Aragon.raw";

            if (!File.Exists(rawFilePath))
            {
                Assert.Ignore(@"Skipping test {0} since file not found: {1}", methodName, rawFilePath);
            }

            var run = InMemoryLcMsRun.GetLcMsRun(rawFilePath, 1.4826, 1.4826);

            sw.Stop();

            Console.WriteLine(@"Reading run: {0:f4} sec", sw.Elapsed.TotalSeconds);

            const int minPrecursorCharge = 3;
            const int maxPrecursorCharge = 30;
            const int tolerancePpm       = 10;
            var       tolerance          = new Tolerance(tolerancePpm);

            sw.Reset();
            sw.Start();
            //var ms1BasedFilter = new Ms1BasedFilter(run, minPrecursorCharge, maxPrecursorCharge, tolerancePpm);
            //
            //var ms1BasedFilter = new Ms1IsotopeTopKFilter(run, minPrecursorCharge, maxPrecursorCharge, tolerancePpm, 20);
            //var ms1BasedFilter = new ProductScorerBasedOnDeconvolutedSpectra(run,
            //    minPrecursorCharge, maxPrecursorCharge,
            //    0, 0,
            //    600.0, 1800.0, new Tolerance(tolerancePpm), null);
            //ms1BasedFilter.CachePrecursorMatchesBinCentric();
            var ms1BasedFilter = new Ms1IsotopeAndChargeCorrFilter(run, new Tolerance(10.0), minPrecursorCharge, maxPrecursorCharge, 3000, 50000, 0.5, 0.5, 0.5, 40);

            //var ms1BasedFilter = new Ms1IsotopeCorrFilter(run, minPrecursorCharge, maxPrecursorCharge, 15, 0.5, 40);

            sw.Stop();

            Console.WriteLine(@"Ms1 filter: {0:f4} sec", sw.Elapsed.TotalSeconds);

            ISequenceFilter ms1Filter = ms1BasedFilter;

            sw.Reset();
            sw.Start();
            const double minProteinMass = 3000.0;
            const double maxProteinMass = 30000.0;
            var          minBinNum      = ProductScorerBasedOnDeconvolutedSpectra.GetBinNumber(minProteinMass);
            var          maxBinNum      = ProductScorerBasedOnDeconvolutedSpectra.GetBinNumber(maxProteinMass);
            var          numComparisons = 0L;

            for (var binNum = minBinNum; binNum <= maxBinNum; binNum++)
            {
                var mass = ProductScorerBasedOnDeconvolutedSpectra.GetMz(binNum);
                numComparisons += ms1Filter.GetMatchingMs2ScanNums(mass).Count();
            }
            sw.Stop();

            Console.WriteLine(@"Calculating #matches per bin: {0:f4} sec", sw.Elapsed.TotalSeconds);

            const string resultFilePath = @"C:\cygwin\home\kims336\Data\TopDown\raw\SBEP_STM_001_02272012_Aragon_4PTMs.icresult";

            if (!File.Exists(resultFilePath))
            {
                Assert.Ignore(@"Skipping test {0} since file not found: {1}", methodName, resultFilePath);
            }

            var tsvReader    = new TsvFileParser(resultFilePath);
            var compositions = tsvReader.GetData("Composition");
            var scanNums     = tsvReader.GetData("ScanNum");
            var charges      = tsvReader.GetData("Charge");
            var scores       = tsvReader.GetData("Score");
            var qvalues      = tsvReader.GetData("QValue");
            var sequences    = tsvReader.GetData("Sequence");

            var sequenceCount = new Dictionary <string, int>();

            for (var i = 0; i < compositions.Count; i++)
            {
                if (qvalues != null)
                {
                    var qValue = Convert.ToDouble(qvalues[i]);
                    if (qValue > 0.01)
                    {
                        continue;
                    }
                }
                else
                {
                    var score = Convert.ToDouble(scores[i]);
                    if (score < 13)
                    {
                        continue;
                    }
                }
                var scanNum      = Convert.ToInt32(scanNums[i]);
                var charge       = Convert.ToInt32(charges[i]);
                var composition  = Composition.Parse(compositions[i]);
                var precursorIon = new Ion(composition, charge);
                var spec         = run.GetSpectrum(scanNum) as ProductSpectrum;
                var isValid      = spec != null && spec.IsolationWindow.Contains(precursorIon.GetMostAbundantIsotopeMz());
                if (!isValid)
                {
                    continue;
                }

                var sequence = sequences[i];
                int count;
                if (sequenceCount.TryGetValue(sequence, out count))
                {
                    sequenceCount[sequence] = count + 1;
                }
                else
                {
                    sequenceCount[sequence] = 1;
                }
            }
            //var sequences = tsvReader.GetData("Annotation");

            var seqSet             = new HashSet <string>();
            var allSeqSet          = new HashSet <string>();
            var numUnfilteredSpecs = 0;
            var totalSpecs         = 0;

            for (var i = 0; i < compositions.Count; i++)
            {
                if (qvalues != null)
                {
                    var qValue = Convert.ToDouble(qvalues[i]);
                    if (qValue > 0.01)
                    {
                        continue;
                    }
                }
                else
                {
                    var score = Convert.ToDouble(scores[i]);
                    if (score < 13)
                    {
                        continue;
                    }
                }
                var scanNum      = Convert.ToInt32(scanNums[i]);
                var charge       = Convert.ToInt32(charges[i]);
                var composition  = Composition.Parse(compositions[i]);
                var precursorIon = new Ion(composition, charge);
                var spec         = run.GetSpectrum(scanNum) as ProductSpectrum;
                var isValid      = spec != null && spec.IsolationWindow.Contains(precursorIon.GetMostAbundantIsotopeMz());
                if (!isValid)
                {
                    continue;
                }

                ++totalSpecs;

                var precursorScanNum = run.GetPrecursorScanNum(scanNum);
                var precursorSpec    = run.GetSpectrum(precursorScanNum);
                var corr1            = precursorSpec.GetCorrScore(precursorIon, tolerance, 0.1);

                var nextScanNum = run.GetNextScanNum(scanNum, 1);
                var nextSpec    = run.GetSpectrum(nextScanNum);
                var corr2       = nextSpec.GetCorrScore(precursorIon, tolerance, 0.1);

                var corr3 = ms1Filter.GetMatchingMs2ScanNums(composition.Mass).Contains(scanNum) ? 1 : 0;
                if (corr3 == 1)
                {
                    numUnfilteredSpecs++;
                    seqSet.Add(sequences[i]);
                }
                allSeqSet.Add(sequences[i]);

                //var xic = run.GetFullPrecursorIonExtractedIonChromatogram(precursorIon.GetMostAbundantIsotopeMz(), tolerance);
                ////xic.Display();
                //var apexScanNum = xic.GetNearestApexScanNum(run.GetPrecursorScanNum(scanNum), false);
                //var apexSpec = run.GetSpectrum(apexScanNum);
                //var corr3 = apexSpec.GetCorrScore(precursorIon, tolerance, 0.1);

                var corrMax = new[] { corr1, corr2, corr3 }.Max();

                Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}", scanNum, precursorScanNum, corr1, nextScanNum, corr2, corr3, corrMax, sequenceCount[sequences[i]]);
            }

            Console.WriteLine("TotalNumComparisons: {0}", numComparisons);
            Console.WriteLine("AverageNumComparisons: {0:f2}", numComparisons / (double)(maxBinNum - minBinNum + 1));
            Console.WriteLine("SuccessRate: {0:f2} {1} / {2}", numUnfilteredSpecs / (double)totalSpecs, numUnfilteredSpecs, totalSpecs);
            Console.WriteLine("NumUniqueSequences: {0:f2}, {1} / {2}", seqSet.Count / (double)allSeqSet.Count, seqSet.Count, allSeqSet.Count);

            Console.WriteLine(@"Elapsed Time: {0:f4} sec", sw.Elapsed.TotalSeconds);
        }
 public override void OnModuleDisabled()
 {
     stopwatch.Stop();
     stopwatch.Reset();
 }
예제 #59
0
        public void FilteringEfficiencyQcShew()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;

            Utils.ShowStarting(methodName);

            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            const string rawFilePath = @"C:\cygwin\home\kims336\Data\TopDownQCShew\raw\QC_ShewIntact_2ug_3k_CID_4Apr14_Bane_PL011402.raw";

            if (!File.Exists(rawFilePath))
            {
                Assert.Ignore(@"Skipping test {0} since file not found: {1}", methodName, rawFilePath);
            }

            var run = InMemoryLcMsRun.GetLcMsRun(rawFilePath, 1.4826, 1.4826);

            sw.Stop();

            Console.WriteLine(@"Reading run: {0:f4} sec", sw.Elapsed.TotalSeconds);

            const int minPrecursorCharge = 3;
            const int maxPrecursorCharge = 30;
            const int tolerancePpm       = 10;
            var       tolerance          = new Tolerance(tolerancePpm);

            sw.Reset();
            sw.Start();
            var ms1BasedFilter = new Ms1IsotopeAndChargeCorrFilter(run, new Tolerance(10.0), minPrecursorCharge, maxPrecursorCharge, 3000, 50000, 0.7, 0.7, 0.7, 40);

            //var ms1BasedFilter = new Ms1IsotopeCorrFilter(run, minPrecursorCharge, maxPrecursorCharge, 15, 0.5, 40);

            sw.Stop();

            Console.WriteLine(@"Ms1 filter: {0:f4} sec", sw.Elapsed.TotalSeconds);

            ISequenceFilter ms1Filter = ms1BasedFilter;

            sw.Reset();
            sw.Start();
            const double minProteinMass = 3000.0;
            const double maxProteinMass = 30000.0;
            var          minBinNum      = ProductScorerBasedOnDeconvolutedSpectra.GetBinNumber(minProteinMass);
            var          maxBinNum      = ProductScorerBasedOnDeconvolutedSpectra.GetBinNumber(maxProteinMass);
            var          numComparisons = 0L;

            for (var binNum = minBinNum; binNum <= maxBinNum; binNum++)
            {
                var mass = ProductScorerBasedOnDeconvolutedSpectra.GetMz(binNum);
                numComparisons += ms1Filter.GetMatchingMs2ScanNums(mass).Count();
            }
            sw.Stop();

            Console.WriteLine(@"Calculating #matches per bin: {0:f4} sec", sw.Elapsed.TotalSeconds);

            //const string prot =
            //    "ADVFHLGLTKAMLDGATLAIVPGDPERVKRIAELMDNATFLASHREYTSYLAYADGKPVVICSTGIGGPSTSIAVEELAQLGVNTFLRVGTTGAIQPHVNVGDVIVTQASVRLDGASLHFAPMEFPAVANFECTTAMVAACRDAGVEPHIGVTASSDTFYPGQERYDTVTGRVTRRFAGSMKEWQDMGVLNYEMESATLFTMCATQGWRAACVAGVIVNRTQQEIPDEATMKKTEVSAVSIVVAAAKKLLA";
            //var protMass = (new AminoAcidSet().GetComposition(prot) + Composition.H2O).Mass;
            //Console.WriteLine("************ScanNums: " + string.Join("\t", ms1Filter.GetMatchingMs2ScanNums(protMass)));

            const string resultFilePath = @"C:\cygwin\home\kims336\Data\TopDownQCShew\MSAlign\NoMod.tsv";

            if (!File.Exists(resultFilePath))
            {
                Assert.Ignore(@"Skipping test {0} since file not found: {1}", methodName, resultFilePath);
            }

            var tsvReader = new TsvFileParser(resultFilePath);
            var scanNums  = tsvReader.GetData("Scan(s)");
            var charges   = tsvReader.GetData("Charge");
            var scores    = tsvReader.GetData("E-value");
            var sequences = tsvReader.GetData("Peptide");

            //const string resultFilePath = @"C:\cygwin\home\kims336\Data\TopDownQCShew\raw\QC_ShewIntact_2ug_3k_CID_4Apr14_Bane_PL011402_N30_C30.tsv";
            //var tsvReader = new TsvFileParser(resultFilePath);
            //var scanNums = tsvReader.GetData("ScanNum");
            //var charges = tsvReader.GetData("Charge");
            //var scores = tsvReader.GetData("Score");
            //var sequences = tsvReader.GetData("Sequence");

            var aaSet = new AminoAcidSet();

            var seqSet             = new HashSet <string>();
            var allSeqSet          = new HashSet <string>();
            var numUnfilteredSpecs = 0;
            var totalSpecs         = 0;

            for (var i = 0; i < scores.Count; i++)
            {
                var score = Convert.ToDouble(scores[i]);
                if (score > 1E-4)
                {
                    continue;
                }
                //if (score < 10) continue;

                var scanNum = Convert.ToInt32(scanNums[i]);
                var charge  = Convert.ToInt32(charges[i]);

                var sequence = SimpleStringProcessing.GetStringBetweenDots(sequences[i]);
                if (sequence == null || sequence.Contains("("))
                {
                    continue;
                }
                //var sequence = sequences[i];
                var composition = aaSet.GetComposition(sequence) + Composition.H2O;

                var precursorIon = new Ion(composition, charge);
                var spec         = run.GetSpectrum(scanNum) as ProductSpectrum;
                var isValid      = spec != null && spec.IsolationWindow.Contains(precursorIon.GetMostAbundantIsotopeMz());
                if (!isValid)
                {
                    continue;
                }
                ++totalSpecs;

                var precursorScanNum = run.GetPrecursorScanNum(scanNum);
                var precursorSpec    = run.GetSpectrum(precursorScanNum);
                var corr1            = precursorSpec.GetCorrScore(precursorIon, tolerance, 0.1);

                var nextScanNum = run.GetNextScanNum(scanNum, 1);
                var nextSpec    = run.GetSpectrum(nextScanNum);
                var corr2       = nextSpec.GetCorrScore(precursorIon, tolerance, 0.1);

                var corr3 = ms1Filter.GetMatchingMs2ScanNums(composition.Mass).Contains(scanNum) ? 1 : 0;
                if (corr3 == 1)
                {
                    numUnfilteredSpecs++;
                    seqSet.Add(sequences[i]);
                }
                allSeqSet.Add(sequences[i]);

                var corrMax = new[] { corr1, corr2, corr3 }.Max();

                Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", scanNum, precursorScanNum, corr1, nextScanNum, corr2, corr3, corrMax);
            }

            Console.WriteLine("TotalNumComparisons: {0}", numComparisons);
            Console.WriteLine("AverageNumComparisons: {0:f2}", numComparisons / (double)(maxBinNum - minBinNum + 1));
            Console.WriteLine("SuccessRate: {0:f2} {1} / {2}", numUnfilteredSpecs / (double)totalSpecs, numUnfilteredSpecs, totalSpecs);
            Console.WriteLine("NumUniqueSequences: {0:f2}, {1} / {2}", seqSet.Count / (double)allSeqSet.Count, seqSet.Count, allSeqSet.Count);

            Console.WriteLine(@"Elapsed Time: {0:f4} sec", sw.Elapsed.TotalSeconds);
        }
예제 #60
0
        public IEnumerable <DicomCFindResponse> OnCFindRequest(DicomCFindRequest request)
        {
            // you should validate the level of the request. I leave it here since there is a bug in version 3.0.2
            // from version 4 on this should be done
            //if (request.Level != DicomQueryRetrieveLevel.Worklist)
            //{
            //    yield return new DicomCFindResponse(request, DicomStatus.QueryRetrieveUnableToProcess);
            //}
            //else
            //{

            /*        foreach (DicomDataset result in WorklistHandler.FilterWorklistItems(request.Dataset, WorklistServer.CurrentWorklistItems))
             *      {
             *          yield return new DicomCFindResponse(request, DicomStatus.Pending) { Dataset = result };
             *      }
             *      yield return new DicomCFindResponse(request, DicomStatus.Success);
             */
            //}

            // set the connection parameters
            // production envrionment

            /*        var serverIP = "192.168.66.21";
             *      var serverPort = 57300;
             *      var serverAET = "MXVOBB";
             *      var clientAET = "MXVOBB";
             */


            #region Old Code What J8 Thing?
            //bool outOfRange = WorklistItemsProvider.IsOutOfRange(request.Dataset);

            //Logger.Info($"OutofRange: {outOfRange}");
            //Log.Loger($"OutofRange: {outOfRange}");

            //if (outOfRange)
            //{
            //    // if date range is out of cached date range, we just forward the request to query
            //    var worklistItems = WorklistItemsProvider.GetWorkList(request);
            //    foreach (DicomDataset result in worklistItems)
            //    {
            //        yield return new DicomCFindResponse(request, DicomStatus.Pending) { Dataset = result };
            //    }
            //    yield return new DicomCFindResponse(request, DicomStatus.Success);
            //}
            //else
            //{
            //    // if date range is in the cached date range, we filtered the result from the cached data set
            //    foreach (DicomDataset result in WorklistHandler.FilterWorklistItemsByDataset(request.Dataset, WorklistItemsProvider.CurrentWorklistItems, Logger))
            //    {
            //        yield return new DicomCFindResponse(request, DicomStatus.Pending) { Dataset = result };
            //    }
            //    yield return new DicomCFindResponse(request, DicomStatus.Success);
            //}
            #endregion

            //记录查询时间
            System.Diagnostics.Stopwatch stopWatch1 = new System.Diagnostics.Stopwatch();
            stopWatch1.Start();
            DateTime dtRequestBeg = DateTime.Now;
            Logger.Info($"\r\n\r\nOnCFindRequest BeginTime: {dtRequestBeg.ToString("yyyy-MM-dd HH:mm:ss")}");
            Log.Loger($"\r\n\r\nOnCFindRequest BeginTime: {dtRequestBeg.ToString("yyyy-MM-dd HH:mm:ss")}");

            bool outOfRange = WorklistItemsProvider.IsOutOfRange(request.Dataset);

            Logger.Info($"OutofRange: {outOfRange}");
            Log.Loger($"OutofRange: {outOfRange}");

            //var worklistItems = WorklistHandler.NewFilterWLIteamsByDataset(request.Dataset, WorklistItemsProvider.CurrentWorklistItems, Logger);
            //var worklistItems = WorklistHandler.NewFilterWLIteamsByDataset(request.Dataset, WorklistItemsProvider.WorklistItems, Logger);
            var worklistItems = WorklistHandler.NewFilterWLIteamsByDataset(WorklistItemsProvider.QueryWorklistItems(request.Dataset), Logger);
            //worklistItems = WorklistItemsProvider.GetWorkList(request);
            foreach (DicomDataset result in worklistItems)
            {
                yield return(new DicomCFindResponse(request, DicomStatus.Pending)
                {
                    Dataset = result
                });
            }
            yield return(new DicomCFindResponse(request, DicomStatus.Success));

            //记录查询时间
            DateTime dtRequestEnd = DateTime.Now;
            Logger.Info($"OnCFindRequest EndTime: {dtRequestEnd.ToString("yyyy-MM-dd HH:mm:ss")}");
            Log.Loger($"OnCFindRequest EndTime: {dtRequestEnd.ToString("yyyy-MM-dd HH:mm:ss")}");
            stopWatch1.Stop();
            Logger.Info($"OnCFindRequest SpentTime: {stopWatch1.Elapsed.TotalSeconds}");
            Log.Loger($"OnCFindRequest SpentTime: {stopWatch1.Elapsed.TotalSeconds}");
            Log.Loger($"---------------------------------------------------------------------------------\r\n\r\n\r\n");
            stopWatch1.Reset();
        }