Exemple #1
1
        public static int Solution2(Stopwatch timer)
        {
            timer.Restart();

            var a = new HashSet<int>();
            int maxlcm = 1;
            int t = 0;
            var results = new List<int>();

            for (int i = 2; i <= 20; i++)
            {
                int k = i%2 == 0 ? 1 : 2;
                for (int j = k; j < i; j+=2)
                {
                    if (gcd(i, j) == 1)
                    {
                        a.Add(2*i*(i + j));
                    }
                }
            }

            var sortedA = a.OrderBy(v => v).ToArray();

            while (maxlcm < 1000)
            {
                maxlcm = lcm(maxlcm, sortedA[t]);
                results.Add(maxlcm);
                t++;
            }

            int res = results[results.Count - 2];
            timer.Stop();
            return res;
        }
        private static void CountLinkedList(int max)
        {
            WriteLine("Linked lists");

            var stopWatch = new Stopwatch();

            stopWatch.Start();
            var ll = new LinkedList<int>();
            for (var i = 0; i < max; i++)
            {
                ll.AddLast(i);
            }
            stopWatch.Stop();
            WriteLine("Time to initialise: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            WriteLine(ll.Count);
            stopWatch.Stop();
            WriteLine("Time to count with prop: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            WriteLine(ll.Count());
            stopWatch.Stop();
            WriteLine("Time to count with extension method: " + stopWatch.ElapsedMilliseconds);

            WriteLine();
        }
        public void should_be_faster_than_the_fcl_xml_serializer()
        {
            var collection = new List<SpeedTestCollection>();
            collection.AddRange(Enumerable.Range(0, 5).Select(x => new SpeedTestCollection
                {
                    Value0 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList(),
                    Value1 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList(),
                    Value2 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList(),
                    Value3 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList(),
                    Value4 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList()
                }));

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            for (var i = 0; i < 100; i++) Bender.Serializer.Create().SerializeXml(collection);
            stopwatch.Stop();
            var benderSpeed = stopwatch.ElapsedTicks;

            var xmlSerializer = new XmlSerializer(typeof(List<SpeedTestCollection>));
            stopwatch.Start();
            for (var i = 0; i < 100; i++) xmlSerializer.Serialize(new MemoryStream(), collection);
            stopwatch.Stop();
            var xmlSerializerSpeed = stopwatch.ElapsedTicks;

            Debug.WriteLine("Bender speed (ticks): {0:#,##0}", benderSpeed);
            Debug.WriteLine("XmlSerializer speed (ticks): {0:#,##0}", xmlSerializerSpeed);
            (benderSpeed < xmlSerializerSpeed).ShouldBeTrue();
        }
        /// <summary>
        /// DataTable
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="spName"></param>
        /// <param name="sqlParameter"></param>
        /// <param name="dt"></param>
        public static void ExecuteStoredProcedure(this ISqlRepository repository, string spName, SqlParameter[] sqlParameter, DataTable dt)
        {
            using (var conn = repository.Create())
            {
                SqlCommand command = new SqlCommand(spName, conn);
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.Parameters.Clear();
                command.Parameters.AddRange(sqlParameter);
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();

                    conn.Open();

                    sw.Stop();
                    var connOpen = sw.Elapsed.TotalSeconds;
                    sw.Restart();

                    SqlDataAdapter sqlDA = new SqlDataAdapter(command);
                    sqlDA.Fill(dt);

                    sw.Stop();
                    //var execute = sw.Elapsed.TotalSeconds;
                    //Log.SqlServerPerformaceAnalysis(command, connOpen, execute);
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        public void Can_bench_specification_extension_method_performance()
        {
            var stopwatch = new Stopwatch();
            const int trials = 1000;

            ISpecification<int> isGreaterThanThree = new PredicateSpecification<int>(v => v > 3);
            ISpecification<int> isLessThanFive = new PredicateSpecification<int>(v => v < 5);
            var isFour = isGreaterThanThree.And(isLessThanFive);

            stopwatch.Start();
            
            for (var i = 0; i < trials; i++)
            {
                isFour.IsSatisfiedBy(2 + 2);
            }
            stopwatch.Stop();
            Trace.WriteLine(stopwatch.Elapsed);

            stopwatch.Start();
            for (var i = 0; i < trials; i++)
            {
                (2 + 2).Satisfies(isFour);
            }
            stopwatch.Stop();
            Trace.WriteLine(stopwatch.Elapsed);
        }
Exemple #6
0
        public static async Task HowToUseAsyncProperly()
        {
            HttpClient client = new HttpClient();   // add System.Net.Http reference to your project
            
            Stopwatch clock = new Stopwatch();
            clock.Start();

            string microsoft = await client.GetStringAsync("http://www.microsoft.com");
            string msdn = await client.GetStringAsync("http://msdn.microsoft.com");
            string google = await client.GetStringAsync("http://www.google.com");

            clock.Stop();
            System.Console.WriteLine("Took {0:hh\\:mm\\:ss} seconds", clock.Elapsed);

            clock.Reset();
            clock.Start();

            Task microsoftTask =  client.GetStringAsync("http://www.microsoft.com");
            Task msdnTask =  client.GetStringAsync("http://msdn.microsoft.com");
            Task googleTask =  client.GetStringAsync("http://www.google.com");
            await Task.WhenAll(microsoftTask, msdnTask, googleTask);

            clock.Stop();
            System.Console.WriteLine("Took {0:hh\\:mm\\:ss} seconds", clock.Elapsed);
        }
    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Reset();
            // Single call test
            watch.Start ();

            SingleCall ();

            watch.Stop ();
            long elapsedSingle = watch.ElapsedTicks;
            Debug.Log ("Single call: " + elapsedSingle + " ticks");
            watch.Reset();
            // Multicall test
            watch.Start ();

            for(int t = 0; t < Iterations; ++t)
            {
                MultiCall();
            }

            watch.Stop ();
            long elapsedMulti = watch.ElapsedTicks;
            Debug.Log ("Multi call: " + elapsedMulti + " ticks");

            Debug.Log ("Ratio (Multi/Single): " + elapsedMulti / (double)elapsedSingle);

        }
    }
Exemple #8
0
 private void RunTests(Harness harness)
 {
     Clients.All.showmessage("Starting " + harness.Name + " tests...");
     var sw = new Stopwatch();
     sw.Start();
     for (var i = 0; i < OPERATIONS; i++)
     {
         var data = i.ToString();
         harness.Create(data);
     }
     sw.Stop();
     Clients.All.showmessage("Put " + OPERATIONS + " values in " + sw.ElapsedMilliseconds + "ms.");
     sw.Reset();
     sw.Start();
     for (var i = 0; i < OPERATIONS; i++)
     {
         var data = i.ToString();
         harness.Read(data);
     }
     sw.Stop();
     Clients.All.showmessage("Read " + OPERATIONS + " values in " + sw.ElapsedMilliseconds + "ms.");
     sw.Reset();
     sw.Start();
     for (var i = 0; i < OPERATIONS; i++)
     {
         var data = i.ToString();
         harness.Delete(data);
     }
     sw.Stop();
     Clients.All.showmessage("Deleted " + OPERATIONS + " values in " + sw.ElapsedMilliseconds + "ms.");
     Clients.All.showmessage("Completed " + harness.Name + " tests...");
 }
        public override TestResult DoTest(ITestCase testCase, int testCasesNumber, bool singleton)
        {
            var result = new TestResult { Singleton = singleton, TestCasesNumber = testCasesNumber };
            var sw = new Stopwatch();

            var c = new ServiceContainer();
            if (singleton)
            {
                sw.Start();
                c = (ServiceContainer)testCase.SingletonRegister(c);
                sw.Stop();
            }
            else
            {
                sw.Start();
                c = (ServiceContainer)testCase.TransientRegister(c);
                sw.Stop();
            }
            result.RegisterTime = sw.ElapsedMilliseconds;

            sw.Reset();
            result.ResolveTime = DoResolve(sw, testCase, c, testCasesNumber, singleton);

            c.Dispose();

            return result;
        }
Exemple #10
0
        public void Searcher_When_SearcherWarmedUp_SearchIsFaster()
        {
            // Arrange
            var stopwatch = new Stopwatch();
            var indexsource = new FeedsDbContextIndexSource(new FeedsDbEntities(), 100);
            var searcher = new Searcher<Document>(indexsource);

            // Act
            stopwatch.Start();
            var results = searcher.Search("net").ToList();
            stopwatch.Stop();

            var elapsed = stopwatch.ElapsedMilliseconds;
            stopwatch.Reset();

            Debug.WriteLine(elapsed);

            stopwatch.Start();
            results = searcher.Search("net").ToList();
            stopwatch.Stop();

            var elapsed2 = stopwatch.ElapsedMilliseconds;

            Debug.WriteLine(elapsed2);

            // Assert
            Assert.IsTrue(elapsed2 < elapsed);
        }
Exemple #11
0
        public void Performance(ICompressor compressor)
        {
            Trace.WriteLine("---------" + compressor.GetType() + "---------");
            byte[] indata = Encoding.UTF8.GetBytes(testData);

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            byte[] result = null;
            foreach (var i in Enumerable.Range(0,100))
            {
                result = compressor.Compress(indata);
            }
            stopwatch.Stop();
            long ticks = stopwatch.ElapsedTicks;
            Trace.WriteLine("Compress: " +  ticks);

            stopwatch.Reset();
            stopwatch.Start();

            byte[] resurrected;
            foreach (var i in Enumerable.Range(0, 100))
            {
                resurrected = compressor.Decompress(result);
            }
            stopwatch.Stop();
            ticks = stopwatch.ElapsedTicks;
            Trace.WriteLine("Decompress: " + ticks);
            Trace.WriteLine("Compression: " + result.Length / (1.0 * indata.Length));
        }
        public void should_be_faster_than_the_fcl_json_deserializer()
        {
            var json = "[" + Enumerable.Range(0, 5).Select(x => "{" +
                    "\"Value0\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
                    "\"Value1\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
                    "\"Value2\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
                    "\"Value3\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
                    "\"Value4\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ] " +
                "}").Aggregate((a, i) => a + ", " + i) + "]";

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            for (var i = 0; i < 100; i++) Bender.Deserializer.Create().DeserializeJson<List<SpeedTestCollection>>(json);
            stopwatch.Stop();
            var benderSpeed = stopwatch.ElapsedTicks;

            var jsonSerializer = new JavaScriptSerializer();
            stopwatch.Start();
            for (var i = 0; i < 100; i++) jsonSerializer.Deserialize<List<SpeedTestCollection>>(json);
            stopwatch.Stop();
            var javascriptSerializerSpeed = stopwatch.ElapsedTicks;

            Debug.WriteLine("Bender speed (ticks): {0:#,##0}", benderSpeed);
            Debug.WriteLine("JavaScriptSerializer speed (ticks): {0:#,##0}", javascriptSerializerSpeed);
            (benderSpeed < javascriptSerializerSpeed).ShouldBeTrue();
        }
Exemple #13
0
	void Start() {

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

		sw.Reset();
		sw.Start();

		for (int i = 0; i < 100000; i++) {
			GameObject a = Instantiate(Resources.Load<GameObject>("A"));
			a.AddComponent<TestA>();
		}

		sw.Stop();


		print("1:"+sw.ElapsedMilliseconds);

		sw.Reset();
		sw.Start();

		for (int i = 0; i < 100000; i++) {
			GameObject a = Instantiate(Resources.Load<GameObject>("B"));
		}

		sw.Stop();
		print("2:" + sw.ElapsedMilliseconds);


	}
        public DemoForm()
        {
            InitializeComponent();

            GraphConfiguration configuration = new GraphConfiguration();
            configuration.AxisXConfiguration.MajorGrid.LineColor = Color.FromArgb(200, 111, 135);
            configuration.Palette.Add(new PaletteItem(){Color = Color.Firebrick, HatchStyle = ChartHatchStyle.BackwardDiagonal});
            configuration.Palette.Add(new PaletteItem() { Color = Color.Black, HatchStyle = ChartHatchStyle.SolidDiamond });
            configuration.GraphSource = new XmlFileGraphSource(){DateTag = "aaa"};
            configuration.SaveToXml("qwe.xml");

            Stopwatch sw = new Stopwatch();
            sw.Start();
            GraphControl gc = graphControl;// new GraphControl();

            gc.SetConfiguration("graphConfig.xml", Size, null);
            sw.Stop();
            #if STOPWATCH
            MessageBox.Show("Time spent for data extraction: " + sw.ElapsedMilliseconds);
            #endif
            sw.Reset();
            sw.Start();
            gc.SaveImage("temp.jpg", ChartImageFormat.Jpeg);
            sw.Stop();
            #if STOPWATCH
            MessageBox.Show("Time spent for data render by Chart control: " + sw.ElapsedMilliseconds);
            #endif
        }
Exemple #15
0
    void LateUpdate()
    {
        //Debug.Log ("Time.time - updateRateRec = " + (Time.time - updateRateRec).ToString());
        if (Time.time - updateRateRec > updateRate)
        {
            Debug.Log("Time.time - updateRateRec = " + (Time.time - updateRateRec).ToString() + "updateRate = " + updateRate.ToString() + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            updateRateRec = Time.time;

            RenderMe();

            //currentMaterial.SetTexture("_Cube", cubemap);
            //GetComponent<Renderer>().material = currentMaterial;
        }

        if (Input.GetKeyUp("space"))
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();//-------------
            RenderMe();
            stopwatch.Stop();
            sb.AppendLine("RenderMe() cost : " + stopwatch.ElapsedMilliseconds);
            stopwatch.Reset();

            stopwatch.Start();//-------------
            //SaveCubemap();
            Texture2D sphereTex = SaveCubeMap2SphericalMap.CreateSphericalMapFromCubeMap(cubemap);
            stopwatch.Stop();
            sb.AppendLine("CreateSphericalMapFromCubeMap() cost : " + stopwatch.ElapsedMilliseconds);
            stopwatch.Reset();

            stopwatch.Start();//-------------
            var bytes = sphereTex.EncodeToJPG();
            File.WriteAllBytes(Application.dataPath + "/cube2sphere.jpg", bytes);
            stopwatch.Stop();
            sb.AppendLine("EncodeToJPG() cost : " + stopwatch.ElapsedMilliseconds);

            System.IO.File.WriteAllText(Application.dataPath + "/CostTime.txt", sb.ToString());
            Debug.Log("save cube map done!!");
            DestroyImmediate(sphereTex);
        }

        bool writeDebugFile = false;
        if (Input.GetKeyUp("d"))
            writeDebugFile = true;
        SaveCubeMap2SphericalMap.RenderDebugSphericalSampleRayInfo(16, 16, writeDebugFile);

        //Debug.Log("Mathf.Sin(Mathf.PI * 0.5f)=" + Mathf.Sin(Mathf.PI * 0.25f).ToString("0.000")  );
        //Debug.Log("Mathf.Cos(Mathf.PI * 0.5f)=" + Mathf.Cos(Mathf.PI * 0.25f).ToString("0.000")  );
    }
		public ActionResult SearchCustomers(HomeViewModel data)
		{
			var client = cloudStorageAccount.CreateCloudTableClient();
			var table = client.GetTableReference(DemoSettings.Storage.CustomerTableName);
			data.MatchedCustomers.Clear();
			var watch = new Stopwatch();

			if (data.UseTable)
			{
				watch.Start();

				foreach (var customer in table.CreateQuery<Customer>().Where(c => data.SearchString == c.Name))
				{
					customer.Value = (int)(customer.Value * 100) / 100.0;
					data.TableCustomers.Add(customer);
				}
				watch.Stop();
				data.TableResponseTime = watch.ElapsedMilliseconds;
			}

			var connection = ConnectionMultiplexer.Connect(new ConfigurationOptions
			{
				EndPoints = { { DemoSettings.CustomerRedisCache.Url, DemoSettings.CustomerRedisCache.Port } },
				Password = DemoSettings.CustomerRedisCache.Password
			});

			var db = connection.GetDatabase();
			watch.Restart();

			var record = db.StringGet("cust:" + data.SearchString.Replace(' ', ':'));
			if (!record.IsNullOrEmpty)
			{
				string[] parts = Encoding.ASCII.GetString(record).Split(':');
				if (parts.Length == 2)
				{
					foreach (var customer in table.CreateQuery<Customer>().Where(c => c.PartitionKey == parts[0] && c.RowKey == parts[1]))
					{
						customer.Value = (int)(customer.Value * 100) / 100.0;
						data.MatchedCustomers.Add(customer);
					}
				}
			}
			watch.Stop();

			data.CachedResponseTime = watch.ElapsedMilliseconds;
			connection.Close(false);

			return View("Index", data);
		}
        static void Main(string[] args)
        {
            const int Size = 10 * 1000 * 1000;

            var ys = new int[Size];

            var stopWatch = new Stopwatch();

            stopWatch.Start();
            for (var i = 0; i < Size; i++)
            {
                ys[i] = i + i;
            }
            stopWatch.Stop();
            WriteLine($"Time to run one loop with many iterations: {stopWatch.ElapsedMilliseconds}");

            var zs = new int[10];

            stopWatch.Restart();
            for (var i = 0; i < Size; i++)
            {
                for (var j = 0; j < zs.Length; j++)
                {
                    zs[j] = j + j;
                }
            }
            stopWatch.Stop();
            WriteLine($"Time to run many loops with few iterations: {stopWatch.ElapsedMilliseconds}");

            stopWatch.Restart();
            for (var i = 0; i < Size; i++)
            {
                ys[i] = f(i);
            }
            stopWatch.Stop();
            WriteLine($"Time to run one loop with a function with many iterations: {stopWatch.ElapsedMilliseconds}");

            stopWatch.Restart();
            for (var i = 0; i < Size; i++)
            {
                for (var j = 0; j < zs.Length; j++)
                {
                    zs[j] = f(j);
                }
            }
            stopWatch.Stop();
            WriteLine($"Time to run with a function many loops with few iterations: {stopWatch.ElapsedMilliseconds}");
        }
Exemple #18
0
        /// <summary>
        /// 计时器结束
        /// </summary>
        /// <param name="watch"></param>
        /// <returns></returns>
        public static string TimerEnd(Diagnostics.Stopwatch watch)
        {
            watch.Stop();
            double costtime = watch.ElapsedMilliseconds;

            return(costtime.ToString());
        }
        public async Task<ActionResult> HourlyMaintenance(string key)
        {
            Stopwatch stopWatch = new Stopwatch();

            // Cleanse the passed string parameters to prevent XSS.
            string cleanKey = Server.HtmlEncode(key);

            if (cleanKey == doctrineShipsServices.Settings.TaskKey)
            {
                // Time the execution of the hourly maintenance.
                stopWatch.Reset();
                stopWatch.Start();

                // Run hourly maintenance tasks.
                await this.doctrineShipsServices.HourlyMaintenance();

                // Stop the clock.
                stopWatch.Stop();

                logger.LogMessage("Hourly Maintenance Successful, Time Taken: " + stopWatch.Elapsed, 2, "Message", MethodBase.GetCurrentMethod().Name);
                return Content("Hourly Maintenance Successful, Time Taken: " + stopWatch.Elapsed);
            }
            else
            {
                logger.LogMessage("Hourly Maintenance Failed, Invalid Key: " + cleanKey, 1, "Message", MethodBase.GetCurrentMethod().Name);
                return Content("Hourly Maintenance Failed, Invalid Key");
            }
        }
        public void PerformanceAdd_WithOnly2ParentWith50000SplitElements()
        {
            var count = 3;
            var counter1 = 1;
            var counter2 = 25001;
            var hierarchy = new Hierarchy<int>(-1);
            Stopwatch timer = new Stopwatch();
            timer.Start();
            hierarchy.Add(-1, 1);
            hierarchy.Add(-1, 25001);
            for (int i = 1; i < 25000; i++)
            {
                hierarchy.Add(1, ++counter1);
                hierarchy.Add(25001, ++counter2);
                count += 2;
                Assert.AreEqual(count, hierarchy.Count, "Count did not increase correctly!");
            }

            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 200);
            counter1 = 1;
            counter2 = 25001;
            for (int i = 1; i < 25000; i++)
            {
                Assert.AreEqual(1, hierarchy.GetParent(++counter1), "Parent did not match!");
                Assert.AreEqual(25001, hierarchy.GetParent(++counter2), "Parent did not match!");
            }

            CollectionAssert.AreEqual(Enumerable.Range(2, 24999).ToArray(), hierarchy.GetChildren(1).ToArray(), "Children did not match!");
            CollectionAssert.AreEqual(Enumerable.Range(25002, 24999).ToArray(), hierarchy.GetChildren(25001).ToArray(), "Children did not match!");
        }
Exemple #21
0
 /// <summary>
 /// Wrap a stopwatch aroudn the execution of an action.
 /// </summary>
 /// <param name="handler">The action to be timed.</param>
 /// <returns>Time elapsed during the handler's execution.</returns>
 public static TimeSpan Stopwatch(Action handler) {
     var s = new Diagnostics.Stopwatch();
     s.Start();
     handler();
     s.Stop();
     return s.Elapsed;
 }
		/// <summary>
		/// Optimizes a media stream and returns the optimized result. The original stream is closed if processing is successful.
		/// </summary>
		public virtual MediaStream Process(MediaStream stream, MediaOptions options)
		{
			Assert.ArgumentNotNull(stream, "stream");

			if (!stream.AllowMemoryLoading)
			{
				Tracer.Error("Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {0}", stream.MediaItem.Path);
				return null;
			}

			var optimizer = CreateOptimizer(stream);

			if (optimizer == null) return null;

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

			var result = optimizer.Optimize(stream);

			sw.Stop();

			if (result.Success)
			{
				stream.Stream.Close();

				Log.Info("Dianoga: optimized {0}.{1} [{2}] (final size: {3} bytes) - saved {4} bytes / {5:p}. Optimized in {6}ms.".FormatWith(stream.MediaItem.MediaPath, stream.MediaItem.Extension, GetDimensions(options), result.SizeAfter, result.SizeBefore - result.SizeAfter, 1 - ((result.SizeAfter / (float)result.SizeBefore)), sw.ElapsedMilliseconds), this);

				return new MediaStream(result.CreateResultStream(), stream.Extension, stream.MediaItem);
			}

			Log.Warn("Dianoga: unable to optimize {0}.{1} because {2}".FormatWith(stream.MediaItem.MediaPath, stream.MediaItem.Extension, result.ErrorMessage), this);

			return null;
		}
        public static void BulkMerge(int nbRecords, Stopwatch clock, StringBuilder sb)
        {
            int recordsToUpdate = nbRecords/2;
            int recordsToInsert = nbRecords - recordsToUpdate;

            var listToInsert = new List<EntitySimple>();

            for (int i = 0; i < recordsToInsert; i++)
            {
                listToInsert.Add(new EntitySimple {ColumnInt = i%5});
            }

            using (var ctx = new CodeFirstEntities())
            {
                ctx.EntitySimples.AddRange(listToInsert);

                List<EntitySimple> listToUpdate = ctx.EntitySimples.Take(recordsToUpdate).AsNoTracking().ToList();
                listToUpdate.ForEach(x => x.ColumnInt = x.ColumnInt + 1);

                sb.Append(string.Format("INSERT {0} / UPDATE {1} entities", recordsToInsert, recordsToUpdate));

                clock.Start();
                ctx.BulkMerge(listToUpdate);
                clock.Stop();
            }
        }
        public void Thirty()
        {
            TestContext.DeleteAll(x => x.Entity_Basics);
            TestContext.Insert(x => x.Entity_Basics, 50);

            using (var ctx = new TestContext())
            {
                // BEFORE
                Assert.AreEqual(1225, ctx.Entity_Basics.Sum(x => x.ColumnInt));

                // ACTION
                var clock = new Stopwatch();
                clock.Start();
                var rowsAffected = ctx.Entity_Basics.Where(x => x.ColumnInt > 10 && x.ColumnInt <= 40).Update(x => new Entity_Basic { ColumnInt = 99 }, update =>
                {
                    update.BatchDelayInterval = 50;
                    update.BatchSize = 5;
                });
                clock.Stop();

                // AFTER
                Assert.AreEqual(460, ctx.Entity_Basics.Sum(x => x.ColumnInt));
                Assert.AreEqual(30, rowsAffected);
                Assert.IsTrue(clock.ElapsedMilliseconds > 250 && clock.ElapsedMilliseconds < 600);
            }
        }
Exemple #25
0
 //https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/NewTask/NewTask.cs
 static void Enqueue(string queueName, string hostName, string msg, int cycles)
 {
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     var factory = new ConnectionFactory() { HostName = hostName };
     factory.UserName = "******";
     factory.Password = "******";
     using (var connection = factory.CreateConnection())
     {
         using (var channel = connection.CreateModel())
         {
             byte[] body;
             QueueDeclareOk res = channel.QueueDeclare(queueName, true, false, false, null);
             if (msg != null)
                 body = Encoding.UTF8.GetBytes(msg);
             else
                 body = new byte[0];
             var properties = channel.CreateBasicProperties();
             properties.SetPersistent(true);
             sw.Start();
             for (int n = 0; n < cycles; ++n)
             {
                 channel.BasicPublish("", queueName, properties, body);
             }
             sw.Stop();
         }
     }
     Console.WriteLine(" [x] Enqueue {0} with count = {1}, time = {2} ms", "", cycles, sw.ElapsedMilliseconds);
 }
        public void SetUp()
        {
            var stopwatch = new Stopwatch();
            _pack = new ConventionPack();
            _pack.AddRange(new IConvention[] 
            {
                new TrackingBeforeConvention(stopwatch) { Name = "1" },
                new TrackingMemberConvention(stopwatch) { Name = "3" },
                new TrackingAfterConvention(stopwatch) { Name = "5" },
                new TrackingMemberConvention(stopwatch) { Name = "4" },
                new TrackingAfterConvention(stopwatch) { Name = "6" },
                new TrackingBeforeConvention(stopwatch) { Name = "2" },
            });
            _subject = new ConventionRunner(_pack);

            var classMap = new BsonClassMap<TestClass>(cm =>
            {
                cm.MapMember(t => t.Prop1);
                cm.MapMember(t => t.Prop2);
            });

            stopwatch.Start();
            _subject.Apply(classMap);
            stopwatch.Stop();
        }
        public ActionResult RefreshContracts(string key, string force, string batchSize)
        {
            Stopwatch stopWatch = new Stopwatch();

            // Cleanse the passed string parameters to prevent XSS.
            string cleanKey = Server.HtmlEncode(key);
            bool cleanForce = Conversion.StringToBool(Server.HtmlEncode(force), false);
            int cleanBatchSize = Conversion.StringToInt32(Server.HtmlEncode(batchSize), 10);

            if (cleanKey == doctrineShipsServices.Settings.TaskKey)
            {
                // Time the execution of the contract refresh.
                stopWatch.Reset();
                stopWatch.Start();

                // Check sales agents and refresh their contracts if required. Also update various contract counts.
                this.doctrineShipsServices.RefreshContracts(cleanForce, cleanBatchSize);
                
                // Stop the clock.
                stopWatch.Stop();

                logger.LogMessage("Contract Refresh Successful, Time Taken: " + stopWatch.Elapsed, 2, "Message", MethodBase.GetCurrentMethod().Name);
                return Content("Contract Refresh Successful, Time Taken: " + stopWatch.Elapsed);
            }
            else
            {
                logger.LogMessage("Contract Refresh Failed, Invalid Key: " + cleanKey, 1, "Message", MethodBase.GetCurrentMethod().Name);
                return Content("Contract Refresh Failed, Invalid Key");
            }
        }
        internal static void TimeInvoke(this EventHandler events, object sender, EventArgs args)
        {
            var sw = new Diagnostics.Stopwatch();

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

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

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

                        timingPair [ev.Method] = previousTime.Add(sw.Elapsed);
                    }
                } catch (Exception ex) {
                    LoggingService.LogInternalError(ex);
                }
            }
        }
Exemple #29
0
        public void TestSequenceEnumerationParallel2()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;
            TestUtils.ShowStarting(methodName);

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

            const string dbFile = @"\\proto-2\UnitTest_Files\InformedProteomics_TestFiles\MSPathFinderT\ID_002216_235ACCEA.fasta";
            var db = new FastaDatabase(dbFile);
            db.Read();
            var indexedDb = new IndexedDatabase(db);
            var arr = db.Characters().ToArray();

            sw.Start();
            //var annotationsAndOffsets = indexedDb.AnnotationsAndOffsetsNoEnzyme(7, 30);
            //            var num = annotationsAndOffsets.AsParallel().LongCount(annotationsAndOffset => annotationsAndOffset.Annotation.IndexOf('W') >= 0);
            //var num = annotationsAndOffsets.LongCount(annotationsAndOffset => annotationsAndOffset.Annotation.IndexOf('W') >= 0);
            //var num = arr.AsParallel().Where(c => c == 'W').LongCount();
            var num = 0;
            var sum = 0L;
            //foreach (var c in arr)
            for (var a = 0; a < arr.Length; a++)
            {
                var c = arr[a];
                for (var i = 0; i < c * 10000; i++) sum += i;
                //                Interlocked.Increment(ref num);
                if (++num == 1000) break;
            }

            Console.WriteLine("NumPeptides: {0}", sum);
            sw.Stop();

            Console.WriteLine(@"{0:f4} sec", sw.Elapsed.TotalSeconds);
        }
        public void Should_fail_to_resolve_route_because_it_does_have_an_invalid_condition()
        {
            // Given
            var cache = new FakeRouteCache(with => {
                with.AddGetRoute("/invalidcondition", "modulekey", ctx => false);
            });

            var bootstrapper = new ConfigurableBootstrapper(with =>{
                with.RouteCache(cache);
            });

            var browser = new Browser(bootstrapper);

            // When
            var timer = new Stopwatch();
            timer.Start();

            for (var i = 0; i < numberOfTimesToResolveRoute; i++)
            {
                var result = browser.Get("/invalidcondition");
                result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);
            }

            timer.Stop();

            // Then
            Debug.WriteLine(" took {0} to execute {1} times", timer.Elapsed, numberOfTimesToResolveRoute);
        }
Exemple #31
0
        public static int Solution1(Stopwatch timer)
        {
            timer.Restart();
            int maxCnt = -1;
            int maxN = -1;

            for (int n = 3; n < 1000; n += 1)
            {
                int cnt = 0;
                int maxA = n/3;
                int maxB = n/2;
                for (int a = 1; a <= maxA; a++)
                {
                    for (int b = a; b <= maxB; b++)
                    {
                        int c = n - (a + b);
                        if (a*a + b*b == c*c)
                        {
                            cnt++;
                        }
                    }
                }

                if (cnt > maxCnt)
                {
                    maxCnt = cnt;
                    maxN = n;
                }
            }
            timer.Stop();
            return maxN;
        }
 public object Run()
 {
     Stopwatch = Stopwatch.StartNew();
     object result = RunSolution();
     Stopwatch.Stop();
     return result;
 }
Exemple #33
0
 //https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/Worker/Worker.cs
 static void Dequeue(string queueName, string hostName, int expected)
 {
     int count = 0;
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     var factory = new ConnectionFactory() { HostName = hostName };
     factory.UserName = "******";
     factory.Password = "******";
     using (var connection = factory.CreateConnection())
     {
         using (var channel = connection.CreateModel())
         {
             channel.QueueDeclare(queueName, true, false, false, null);
             channel.BasicQos(0, 1, false);
             var consumer = new QueueingBasicConsumer(channel);
             channel.BasicConsume(queueName, false, consumer);
             sw.Start();
             while (count < expected)
             {
                 BasicDeliverEventArgs ea = consumer.Queue.Dequeue();
                 var body = ea.Body;
                 var message = Encoding.UTF8.GetString(body);
                 channel.BasicAck(ea.DeliveryTag, false);
                 ++count;
             }
             sw.Stop();
         }
     }
     Console.WriteLine(" [x] {0} messages dequeued in time = {1} ms", count, sw.ElapsedMilliseconds);
 }
Exemple #34
0
        static void TimeInvoke(Action <Delegate, object, EventArgs> call, Delegate[] del, object sender, EventArgs args, object groupId)
        {
            var sw = new Diagnostics.Stopwatch();

            foreach (var ev in del)
            {
                try {
                    sw.Restart();
                    call(ev, sender, args);
                    sw.Stop();

                    RecordTime(groupId ?? sender, ev.Method, sw.Elapsed);
                } catch (Exception ex) {
                    LoggingService.LogInternalError(ex);
                }
            }
        }
Exemple #35
0
        static void Main(string[] args)
        {
            int min, max;

            nc = 2;
            n  = 100000000;
            A  = new int[n];
            Random r = new Random();

            for (int j = 0; j < n; j++)
            {
                A[j] = r.Next(1000);
            }
            System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch();
            sWatch.Start();
            min = A[0];
            for (int i = 1; i < n; i++)
            {
                if (A[i] < min)
                {
                    min = A[i];
                }
            }
            max = A[0];
            for (int i = 1; i < n; i++)
            {
                if (A[i] > max)
                {
                    max = A[i];
                }
            }

            Console.WriteLine(min);
            Console.WriteLine(max);

            sWatch.Stop();

            Console.WriteLine("Sequential algorithm = {0} ms.", sWatch.ElapsedMilliseconds.ToString());


            InputData[] ClArr = new InputData[nc];
            for (int i = 0; i < nc; i++)
            {
                ClArr[i] = new InputData();
            }

            int step = (Int32)(n / nc);

            int c = -1;

            for (int i = 0; i < nc; i++)
            {
                ClArr[i].start = c + 1;
                ClArr[i].stop  = c + step;
                c = c + step;
            }
            Dispatcher      d  = new Dispatcher(nc, "Test Pool");
            DispatcherQueue dq = new DispatcherQueue("Test Queue", d);
            Port <int>      p  = new Port <int>();


            for (int i = 0; i < nc; i++)
            {
                Arbiter.Activate(dq, new Task <InputData, Port <int> >(ClArr[i], p, MinMax));
            }

            Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(int[] array)
                                                             { }));
        }
        /// <summary>
        /// Sends activities to the conversation.
        /// </summary>
        /// <param name="turnContext">The context object for the turn.</param>
        /// <param name="activities">The activities to send.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        /// <remarks>If the activities are successfully sent, the task result contains
        /// an array of <see cref="ResourceResponse"/> objects containing the IDs that
        /// the receiving channel assigned to the activities.</remarks>
        /// <seealso cref="ITurnContext.OnSendActivities(SendActivitiesHandler)"/>
        public override async Task <ResourceResponse[]> SendActivitiesAsync(ITurnContext turnContext, Activity[] activities, CancellationToken cancellationToken)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (activities == null)
            {
                throw new ArgumentNullException(nameof(activities));
            }

            if (activities.Length == 0)
            {
                throw new ArgumentException("Expecting one or more activities, but the array was empty.", nameof(activities));
            }

            var responses = new ResourceResponse[activities.Length];

            /*
             * NOTE: we're using for here (vs. foreach) because we want to simultaneously index into the
             * activities array to get the activity to process as well as use that index to assign
             * the response to the responses array and this is the most cost effective way to do that.
             */
            for (var index = 0; index < activities.Length; index++)
            {
                var activity = activities[index];
                if (string.IsNullOrWhiteSpace(activity.Id))
                {
                    activity.Id = Guid.NewGuid().ToString("n");
                }

                var response = default(ResourceResponse);

                if (activity.Type == ActivityTypesEx.Delay)
                {
                    // The Activity Schema doesn't have a delay type build in, so it's simulated
                    // here in the Bot. This matches the behavior in the Node connector.
                    var delayMs = (int)activity.Value;
                    await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);

                    // No need to create a response. One will be created below.
                }

                // set SemanticAction property of the activity properly
                EnsureActivitySemanticAction(turnContext, activity);

                if (activity.Type != ActivityTypes.Trace ||
                    (activity.Type == ActivityTypes.Trace && activity.ChannelId == "emulator"))
                {
                    var requestPath = $"/activities/{activity.Id}";
                    var request     = StreamingRequest.CreatePost(requestPath);

                    // set callerId to empty so it's not sent over the wire
                    activity.CallerId = null;

                    request.SetBody(activity);

                    _botTelemetryClient.TrackTrace($"Sending activity. ReplyToId: {activity.ReplyToId}", Severity.Information, null);

                    var stopWatch = new Diagnostics.Stopwatch();

                    try
                    {
                        stopWatch.Start();
                        response = await SendRequestAsync <ResourceResponse>(request).ConfigureAwait(false);

                        stopWatch.Stop();
                    }
                    catch (Exception ex)
                    {
                        throw new SkillWebSocketCallbackException($"Callback failed. Verb: POST, Path: {requestPath}", ex);
                    }

                    _botTelemetryClient.TrackEvent("SkillWebSocketSendActivityLatency", null, new Dictionary <string, double>
                    {
                        { "Latency", stopWatch.ElapsedMilliseconds },
                    });
                }

                // If No response is set, then defult to a "simple" response. This can't really be done
                // above, as there are cases where the ReplyTo/SendTo methods will also return null
                // (See below) so the check has to happen here.

                // Note: In addition to the Invoke / Delay / Activity cases, this code also applies
                // with Skype and Teams with regards to typing events.  When sending a typing event in
                // these _channels they do not return a RequestResponse which causes the bot to blow up.
                // https://github.com/Microsoft/botbuilder-dotnet/issues/460
                // bug report : https://github.com/Microsoft/botbuilder-dotnet/issues/465
                if (response == null)
                {
                    response = new ResourceResponse(activity.Id ?? string.Empty);
                }

                responses[index] = response;
            }

            return(responses);
        }
Exemple #37
0
        public static void Benchmark2(int total_parents, List <long> testTimes, List <long> testTimes2, ref int rowcount, ref int rowcount2)
        {
            MemoryFileSystemBacked.FlushAll("CEF_Demo");

            // Data set-up is not timed here...
            Benchmark2Setup(total_parents);

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

            watch.Start();

            // With caching enabled, we make 3 passes over the data where we a) use a query to get all parents (only), b) call a method that represents some API to get all phones for said parent, c) increment age on parents where they have a mobile phone, d) apply a possible update for the phones to modify their numbers based on another api method that only accepts a PhoneID (i.e. need to reretrieve some data)
            for (int j = 1; j <= 2; ++j)
            {
                using (CEF.NewServiceScope(new ServiceScopeSettings()
                {
                    UseAsyncSave = true
                }))
                {
                    var parents = new EntitySet <Person>().DBRetrieveSummaryForParents(30);

                    foreach (var parent in parents)
                    {
                        var phones = new EntitySet <Phone>().DBRetrieveByOwner(parent.PersonID, null);
                        rowcount += 1;

                        if ((from a in phones where a.PhoneTypeID == PhoneType.Mobile select a).Any())
                        {
                            parent.Age += 1;
                            parent.DBSave(false);
                            rowcount += 1;
                        }

                        foreach (var phone in phones)
                        {
                            string area = "";

                            switch (phone.PhoneTypeID)
                            {
                            case PhoneType.Home:
                                area = "707";
                                break;

                            case PhoneType.Mobile:
                                area = "415";
                                break;

                            case PhoneType.Work:
                                area = "800";
                                break;
                            }

                            UpdatePhoneAPITest1(phone.AsDynamic().PhoneID, area, ref rowcount);

                            if (!TestValidPhoneAPITest2(phone.AsDynamic().PhoneID, parent.PersonID, ref rowcount))
                            {
                                throw new Exception("Failure!");
                            }
                        }
                    }
                }
            }

            watch.Stop();
            testTimes.Add(watch.ElapsedMilliseconds);

            // Extra verification that results match expected
            if (!Benchmark2Verify(total_parents))
            {
                throw new Exception("Unexpected final result.");
            }
        }
Exemple #38
0
        public void ProcessReceive()
        {
            LogFiler.Log(Category.Info, MethodBase.GetCurrentMethod().DeclaringType.Name + "_" + MethodBase.GetCurrentMethod().Name + ": started receiving data.");

            try
            {
                while (!IsStopped)
                {
                    var watch = new System.Diagnostics.Stopwatch();
                    watch.Start();
                    Task <byte[]> receive = TReceive();
                    ScannerDecode Info    = new ScannerDecode().Decode(receive.Result);

                    if (Info.ID == 1)
                    {
                        RefreshScanner(Info);
                        Tuple <float, float> angleinfo = ScannerFunctionality.GetAngleId1(receive.Result);
                        Degree          = angleinfo.Item1;
                        AngleDifference = angleinfo.Item2;
                    }
                    else if (Info.ID == 6)
                    {
                        if (BlockOrderCorrect(Info.Block))
                        {
                            ExpandScanner(Info, receive.Result);

                            // if the id6 telegramblocks are finished - split the distance based on the scannergap information (not visible area)
                            // if its not getting split, the averaging will create datapoints where the scanner couldnt be able to see at all - leads to consequential errors
                            if (Id6Complete())
                            {
                                Distance = ScannerFunc.GetProcessedDistance(Id6Distance.ToList());

                                if (Mainframe.IsNormalizedbyMedian[Tag])
                                {
                                    Distance = ScannerFunc.GetMedianAverageArray(Distance.ToList());
                                }

                                XYCoord = ScannerFunc.GetXYCoordinate(Distance.ToList(), this);

                                XYCoordinate = ScannerFunctionality.MergeXYArray(XYCoord.ToList());
                                OnScannerRaw(this, XYCoordinate.ToList());

                                List <List <Tuple <int, int, int> > > Normalizer = new List <List <Tuple <int, int, int> > >();
                                List <Tuple <int, int, int> >         Normalized = new List <Tuple <int, int, int> >();

                                // try to accomplish the necessary kinds of averaging the distance sent by the scanner
                                // data averaged by time
                                if (Mainframe.IsNormalizedbyTime[Tag])
                                {
                                    List <Tuple <int, int, int> > xycollection = new List <Tuple <int, int, int> >(XYCoordinate);
                                    XYCollection[RingBufferCount] = xycollection;

                                    List <List <Tuple <int, int, int> > > xycolle = new List <List <Tuple <int, int, int> > >(XYCoord);
                                    XYColl[RingBufferCount] = xycolle;

                                    RingBufferCount++;
                                    CountTimeAverage++;

                                    if (RingBufferCount == Mainframe.NormalizebyTimeCountStoredData[Tag])
                                    {
                                        RingBufferCount = 0;
                                    }

                                    if (CountTimeAverage == Mainframe.NormalizebyTimeCountDataAverage[Tag])
                                    {
                                        Normalizer       = ScannerFunc.NormalizationByTime(RingBufferCount, XYColl);
                                        CountTimeAverage = 0;
                                    }
                                }
                                else
                                {
                                    Normalizer = XYCoord;
                                }

                                if (Normalizer.Count != 0)
                                {
                                    if (Mainframe.IsNormalizedbyTriangle[Tag])
                                    {
                                        Normalizer = ScannerFunc.Normalization(Normalizer.ToList());
                                    }

                                    Normalized = ScannerFunctionality.MergeNormalizeArray(Normalizer.ToList());

                                    Normalized = ScannerFunc.ChangePositionOfXY(Normalized.ToList());

                                    NormalizedData = Normalized;
                                    OnScannerNormalized(this, new List <Tuple <int, int, int> >(NormalizedData));

                                    List <Tuple <int, int, int> > Analyser = new List <Tuple <int, int, int> >(Normalized);
                                    AnalyseData = Analyser;
                                }

                                if (watch.IsRunning)
                                {
                                    watch.Stop();
                                    LogFiler.Log(Category.Info, "normalise" + watch.ElapsedMilliseconds.ToString());
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogFiler.Log(Category.Error, MethodBase.GetCurrentMethod().DeclaringType.Name + "_" + MethodBase.GetCurrentMethod().Name + ": " + ex.Message);
            }
        }
        private void QueryResults()
        {
            if (!string.IsNullOrEmpty(QueryText))
            {
                var queryTimer = new System.Diagnostics.Stopwatch();
                queryTimer.Start();
                _updateSource?.Cancel();
                var currentUpdateSource = new CancellationTokenSource();
                _updateSource = currentUpdateSource;
                var currentCancellationToken = _updateSource.Token;
                _updateToken = currentCancellationToken;

                ProgressBarVisibility = Visibility.Hidden;
                _isQueryRunning       = true;
                var query = QueryBuilder.Build(QueryText.Trim(), PluginManager.NonGlobalPlugins);
                if (query != null)
                {
                    // handle the exclusiveness of plugin using action keyword
                    RemoveOldQueryResults(query);

                    _lastQuery = query;
                    var plugins = PluginManager.ValidPluginsForQuery(query);

                    Task.Run(() =>
                    {
                        // so looping will stop once it was cancelled
                        var parallelOptions = new ParallelOptions {
                            CancellationToken = currentCancellationToken
                        };
                        try
                        {
                            Parallel.ForEach(plugins, parallelOptions, plugin =>
                            {
                                if (!plugin.Metadata.Disabled)
                                {
                                    var results = PluginManager.QueryForPlugin(plugin, query);
                                    if (Application.Current.Dispatcher.CheckAccess())
                                    {
                                        UpdateResultView(results, plugin.Metadata, query);
                                    }
                                    else
                                    {
                                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                                        {
                                            UpdateResultView(results, plugin.Metadata, query);
                                        }));
                                    }
                                }
                            });
                        }
                        catch (OperationCanceledException)
                        {
                            // nothing to do here
                        }


                        // this should happen once after all queries are done so progress bar should continue
                        // until the end of all querying
                        _isQueryRunning = false;
                        if (currentUpdateSource == _updateSource)
                        { // update to hidden if this is still the current query
                            ProgressBarVisibility = Visibility.Hidden;
                        }

                        queryTimer.Stop();
                        var queryEvent = new LauncherQueryEvent()
                        {
                            QueryTimeMs = queryTimer.ElapsedMilliseconds,
                            NumResults  = Results.Results.Count,
                            QueryLength = query.RawQuery.Length
                        };
                        PowerToysTelemetry.Log.WriteEvent(queryEvent);
                    }, currentCancellationToken);
                }
            }
            else
            {
                Results.SelectedItem = null;
                Results.Clear();
                Results.Visibility = Visibility.Collapsed;
            }
        }
    public Vector3 ElectricField(Vector3 pos, int rigidbodyId = -1, int excludeConductors = 0)
    {
        // I absorbed the 1/(4pi epsilon0) factor into the units of electric charge strength.
        Vector3 E = ambientElectricField;

        if (iterationCount == 0)
        {
            framesCount++;
            if (framesCount % 500 == 0 && framesCount > 0)
            {
                //Debug.Log(sw.ElapsedMilliseconds);
                sw.Reset();
            }

#if USE_ARRAY
            positions = new Vector3[staticChargeCount];
            strengths = new float[staticChargeCount];
            rids      = staticChargePosition.Keys.ToArray();
            int[] strengthKeys = staticChargePosition.Keys.ToArray();
            for (int i = 0; i < staticChargeCount; i++)
            {
                positions[i] = staticChargePosition[rids[i]].Values.First();
                strengths[i] = staticChargeStrength[strengthKeys[i]].Values.First();
            }
#endif
        }
        iterationCount++;

        sw.Start();

#if USE_ARRAY
        for (int i = 0; i < staticChargeCount; i++)
        {
            if (rids[i] != rigidbodyId && (rigidbodyId < 0 || !Colliding(rids[i], rigidbodyId)))
            {
                Vector3 opos = positions[i];
                float   ostr = strengths[i];

                Vector3 r = (pos - opos);
                E += r.normalized * ostr / r.sqrMagnitude / (4.0f * Mathf.PI * 8.8541878176e-12f);
            }
        }
#endif
#if USE_DICTIONARY
        //original version

        foreach (int rId in staticChargePosition.Keys)
        {
            if (rId != rigidbodyId && (rigidbodyId < 0 || !Colliding(rId, rigidbodyId)))
            {
                foreach (int sId in staticChargePosition[rId].Keys)
                {
                    Vector3 opos = staticChargePosition[rId][sId];
                    float   ostr = staticChargeStrength[rId][sId];

                    Vector3 r = (pos - opos);
                    E += r.normalized * ostr / r.sqrMagnitude / (4.0f * Mathf.PI * 8.8541878176e-12f);
                }
            }
        }
#endif
        sw.Stop();
        return(E);
    }
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.Paint"/> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"/> that contains the event data. </param>
        protected override void OnPaint(PaintEventArgs e)
        {
            //Debug.WriteLine("OnPaint =================1");
            if (Document == null || _suspendPaintCount > 0)
            {
                return;
            }

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

            var offset = GetScrollOffset();
            var bounds = GetScrollClientArea();

            using (var brush = new SolidBrush(BackColor))
            {
                e.Graphics.FillRectangle(brush, e.ClipRectangle);
            }

            _visiblePageStart = -1;
            _visiblePageEnd   = -1;

            for (int page = 0; page < Document.getPageSizes().Count; page++)
            {
                var pageCache = _pageCache[page];
                var rectangle = pageCache.OuterBounds;
                rectangle.Offset(offset.Width, offset.Height);

                if (_visiblePageStart == -1 && rectangle.Bottom >= 0)
                {
                    _visiblePageStart = page;
                }
                if (_visiblePageEnd == -1 && rectangle.Top > bounds.Height)
                {
                    _visiblePageEnd = page - 1;
                }

                if (e.ClipRectangle.IntersectsWith(rectangle))
                {
                    var pageBounds = pageCache.Bounds;
                    //Debug.WriteLine("OnPaint =================2 : " + page + ",[" + pageBounds.X + "," + pageBounds.Y + "," + pageBounds.Width + "," + pageBounds.Height);
                    pageBounds.Offset(offset.Width, offset.Height);

                    e.Graphics.FillRectangle(Brushes.White, pageBounds);

                    //Debug.WriteLine("OnPaint =================3 : " + page + ",[" + pageBounds.X + "," + pageBounds.Y + "," + pageBounds.Width + "," + pageBounds.Height);
                    DrawPageImage(e.Graphics, page, pageBounds);
                }
            }

            if (_visiblePageStart == -1)
            {
                _visiblePageStart = 0;
            }
            if (_visiblePageEnd == -1)
            {
                _visiblePageEnd = Document.getPageCount() - 1;
            }

            stopwatch.Stop();
            Debug.WriteLine("OnPaint time : " + stopwatch.Elapsed.TotalSeconds); //这里是输出的总运行秒数,精确到毫秒的
        }
Exemple #42
0
 public void Stop()
 {
     sw.Stop();
 }
        public static void Main(string[] args)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();
            SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);

            //if(!isclosing)
            //{
            Program obj = new Program();
            string  filepath, DownloadPath = string.Empty;
            int     threadCount = 1;

            if (args.Length == 0)
            {
                filepath     = ConfigurationManager.AppSettings["URL_FILE_PATH"];;
                DownloadPath = ConfigurationManager.AppSettings["DOWNLOAD_FILE_PATH"];
                string temp = ConfigurationManager.AppSettings["THREAD_COUNT"];

                int.TryParse(temp, out threadCount);
                if (threadCount < 0 || threadCount > 10 || threadCount == 0)
                {
                    threadCount = 1;
                }

                if (obj.verifiyFilePath(filepath) && obj.veryfyFileExt(filepath) && obj.verifyDownloadPath(DownloadPath))
                {
                    fileLogger.Instance().WriteToLog("   ## Starting Run", PARENT_THREAD);
                    List <string> listOfurls = new List <string>();
                    listOfurls = obj.getUrlsFromFile(filepath);
                    if (listOfurls.Count > 0)
                    {
                        var cts     = new CancellationTokenSource();
                        var options = new ParallelOptions()
                        {
                            MaxDegreeOfParallelism = threadCount
                        };

                        options.CancellationToken = cts.Token;
                        Parallel.ForEach(listOfurls, options, url =>
                        {
                            try
                            {
                                if (url.StartsWith("http"))
                                {
                                    download httpObj = new httpdownload(url, DownloadPath, listOfurls.IndexOf(url), "THREAD_ID_" + Thread.CurrentThread.ManagedThreadId.ToString() + "_URL_NO_" + listOfurls.IndexOf(url));
                                }
                                else if (url.StartsWith("ftp"))
                                {
                                    download ftpObj = new ftpdownload(url, DownloadPath, listOfurls.IndexOf(url), "THREAD_ID_" + Thread.CurrentThread.ManagedThreadId.ToString() + "_URL_NO_" + listOfurls.IndexOf(url));
                                }
                                else if (url.StartsWith("sftp"))
                                {
                                    download sftpObj = new sftpdownload(url, DownloadPath, listOfurls.IndexOf(url), "THREAD_ID_" + Thread.CurrentThread.ManagedThreadId.ToString() + "_URL_NO_" + listOfurls.IndexOf(url));
                                }
                                else
                                {
                                    fileLogger.Instance().WriteToLog("   Skipping URL:" + url + " as this program does not suppport it", Thread.CurrentThread.ManagedThreadId.ToString() + "_URL_NO_" + listOfurls.IndexOf(url));
                                }
                                options.CancellationToken.ThrowIfCancellationRequested();
                            }
                            catch (Exception e)
                            {
                                fileLogger.Instance().WriteToLog("   ERROR" + e.Message, PARENT_THREAD);
                            }
                        });
                        cts.Cancel();
                    }
                    else
                    {
                        Console.WriteLine("  No URLs to Process.");
                        fileLogger.Instance().WriteToLog("   No URLs to Process.", PARENT_THREAD);
                    }
                }
                else
                {
                    fileLogger.Instance().WriteToLog("   Invalid config..", PARENT_THREAD);
                }
            }
            else
            {
                Console.WriteLine("Invalid Syntax.");
                Console.WriteLine("Correct Syntax: DownloadManager.exe ");
                fileLogger.Instance().WriteToLog("   Invalid Syntax...      Correct Syntax: DownloadManager.exe ", PARENT_THREAD);
            }

            fileLogger.Instance().WriteToLog("   ## Ending Run", PARENT_THREAD);
            obj.cleanup(DownloadPath);

            watch.Stop();

            Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
            Console.WriteLine("Done.");
        }
Exemple #44
0
 public void Dispose()
 {
     _watch.Stop();
     DebugLog($"{_msg}: {_watch.ElapsedMilliseconds}ms");
 }
Exemple #45
0
        static void Main(string[] args)
        {
            int i;

            nc = 2;
            n  = 100000000;

            a = new int[n];
            b = new int[nc];

            Random r = new Random();

            for (int j = 0; j < n; j++)
            {
                a[j] = r.Next(100);
            }

            System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch();
            sWatch.Start();
            for (i = 0; i <= n; i++)
            {
                for (int j = i; i <= n; i++)
                {
                    if (a[j] > a[j + 1])
                    {
                        int e = a[j]; //change for elements
                        a[j]     = a[j + 1];
                        a[j + 1] = e;
                    }
                }
            }



            sWatch.Stop();

            Console.WriteLine("Последовательный алгоритм = {0} мс.", sWatch.ElapsedMilliseconds.ToString());



            // создание массива объектов для хранения параметров
            InputData[] ClArr = new InputData[nc];
            for (i = 0; i < nc; i++)
            {
                ClArr[i] = new InputData();
            }
            // делим количество элементов  в массиве на nc частей
            int step = (Int32)(n / nc);
            // заполняем массив параметров
            int c = -1;

            for (i = 0; i < nc; i++)
            {
                ClArr[i].start = c + 1;
                ClArr[i].stop  = c + step;
                ClArr[i].i     = i;
                c = c + step;
            }
            Dispatcher      d  = new Dispatcher(nc, "Test Pool");
            DispatcherQueue dq = new DispatcherQueue("Test Queue", d);
            Port <int>      p  = new Port <int>();


            for (i = 0; i < nc; i++)
            {
                Arbiter.Activate(dq, new Task <InputData, Port <int> >(ClArr[i], p, Mul));
            }

            Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(int[] array)
                                                             {   }));
        }
Exemple #46
0
        private void Open_Click(object sender, EventArgs e)
        {
            Bitmap         image;
            OpenFileDialog open_dialog = new OpenFileDialog();

            if (open_dialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    filename  = open_dialog.FileName;
                    extension = Path.GetExtension(filename);
                    FileInfo fi = new FileInfo(open_dialog.FileName);
                    filepath = fi.DirectoryName;
                    fi.CopyTo("copy.tiff", true);
                    if (imageFormat.Contains(extension))
                    {
                        imageLoaded = true;
                        image       = new Bitmap(open_dialog.FileName);
                        string imageString = image.ToString();
                        b           = ImageToByteArray(image);
                        l           = Convert.ToInt32(fi.Length);
                        label1.Text = "Тип файла: изображение";

                        Stopwatch StopwatchRLE = new System.Diagnostics.Stopwatch();
                        StopwatchRLE.Start(); //запуск

                        b2 = ImageRLE(b);
                        int l2 = b2.Length;

                        StopwatchRLE.Stop(); //остановить
                        TimeSpan ts = StopwatchRLE.Elapsed;

                        string elapsedTime = "RLE:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                    ts.Hours, ts.Minutes, ts.Seconds,
                                                                    ts.Milliseconds / 10);
                        //  label4.Text = elapsedTime;
                        //ImageLZW();

                        Stopwatch StopwatchJPEG = new System.Diagnostics.Stopwatch();
                        StopwatchJPEG.Start(); //запуск

                        long lenghtJPG = VaryQualityLevel(filename, filepath + "\\");

                        StopwatchJPEG.Stop(); //остановить
                        TimeSpan ts1 = StopwatchJPEG.Elapsed;

                        string elapsedTime1 = "JPEG:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                      ts1.Hours, ts1.Minutes, ts1.Seconds,
                                                                      ts1.Milliseconds / 10);
                        // label5.Text = elapsedTime1;

                        Stopwatch StopwatchDeflate = new System.Diagnostics.Stopwatch();
                        StopwatchDeflate.Start(); //запуск

                        long lengthDeflate = Deflate("copy.tiff", "book.png");

                        StopwatchDeflate.Stop(); //остановить
                        TimeSpan ts2 = StopwatchDeflate.Elapsed;

                        string elapsedTime2 = "Deflate:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                         ts2.Hours, ts2.Minutes, ts2.Seconds,
                                                                         ts2.Milliseconds / 10);
                        // label6.Text = elapsedTime2;

                        Stopwatch StopwatchBWT = new System.Diagnostics.Stopwatch();
                        StopwatchBWT.Start(); //запуск

                        string outputBWT = BWT(imageString);
                        int    BWTlength = outputBWT.Length;


                        StopwatchBWT.Stop(); //остановить
                        TimeSpan ts3 = StopwatchBWT.Elapsed;

                        List <int> rawList = new List <int>();
                        rawList.Add(l);
                        List <int> rleList = new List <int>();
                        rleList.Add(l2);
                        List <int> deflateList = new List <int>();
                        deflateList.Add(Convert.ToInt32(lengthDeflate));
                        //List<int> lzwList = new List<int>();
                        //lzwList.Add(LZWlength);
                        List <int> jpegList = new List <int>();
                        jpegList.Add(Convert.ToInt32(lenghtJPG));
                        List <int> BWTList = new List <int>();
                        BWTList.Add(BWTlength);
                        chart1.Series[0].Points.DataBindY(rawList);
                        chart1.Series[1].Points.DataBindY(rleList);
                        //chart1.Series[2].Points.DataBindY(lzwList);
                        chart1.Series[3].Points.DataBindY(jpegList);
                        chart1.Series[4].Points.DataBindY(deflateList);
                        chart1.Series[5].Points.DataBindY(BWTList);

                        List <int> timeRLEList = new List <int>();
                        timeRLEList.Add(ts.Seconds / 1000 + ts.Milliseconds);
                        List <int> timeDeflateList = new List <int>();
                        timeDeflateList.Add(ts2.Seconds / 1000 + ts2.Milliseconds);
                        List <int> timeJPEGList = new List <int>();
                        timeJPEGList.Add(ts1.Seconds / 1000 + ts1.Milliseconds);
                        List <int> timeBWTList = new List <int>();
                        timeBWTList.Add(ts3.Seconds / 1000 + ts1.Milliseconds);
                        //List<int> lzwList = new List<int>();
                        //lzwList.Add(LZWlength);
                        chart2.Series[0].Points.DataBindY(timeRLEList);
                        chart2.Series[2].Points.DataBindY(timeJPEGList);
                        //chart1.Series[1].Points.DataBindY(lzwList);
                        chart2.Series[3].Points.DataBindY(timeDeflateList);
                        chart2.Series[4].Points.DataBindY(timeBWTList);
                    }
                    if (textFormat.Contains(extension))
                    {
                        textLoaded  = true;
                        text        = File.ReadAllText(filename);
                        ch          = text.ToCharArray(0, text.Length);
                        l           = text.Length;
                        label1.Text = "Тип файла: текст";

                        Stopwatch StopwatchRLE = new System.Diagnostics.Stopwatch();
                        StopwatchRLE.Start(); //запуск

                        string outputRLE = RunLengthEncoding(text);
                        int    l2        = outputRLE.Length;

                        StopwatchRLE.Stop(); //остановить
                        TimeSpan ts = StopwatchRLE.Elapsed;

                        string elapsedTime = "RLE:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                    ts.Hours, ts.Minutes, ts.Seconds,
                                                                    ts.Milliseconds / 10);
                        //   label4.Text = elapsedTime;

                        Stopwatch StopwatchLZW = new System.Diagnostics.Stopwatch();
                        StopwatchLZW.Start(); //запуск

                        TextLZW();

                        StopwatchLZW.Stop(); //остановить
                        TimeSpan ts1 = StopwatchLZW.Elapsed;

                        string elapsedTime1 = "LZW:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                     ts1.Hours, ts1.Minutes, ts1.Seconds,
                                                                     ts1.Milliseconds / 10);
                        //    label5.Text = elapsedTime1;

                        Stopwatch StopwatchDeflate = new System.Diagnostics.Stopwatch();
                        StopwatchDeflate.Start(); //запуск

                        long lengthDeflate = Deflate("text1.txt", "book.txt");

                        StopwatchDeflate.Stop(); //остановить
                        TimeSpan ts2 = StopwatchDeflate.Elapsed;

                        string elapsedTime2 = "Deflate:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                         ts2.Hours, ts2.Minutes, ts2.Seconds,
                                                                         ts2.Milliseconds / 10);

                        Stopwatch StopwatchBWT = new System.Diagnostics.Stopwatch();
                        StopwatchBWT.Start(); //запуск

                        string outputBWT = BWT(text);
                        int    BWTlength = outputBWT.Length;


                        StopwatchBWT.Stop(); //остановить
                        TimeSpan ts3 = StopwatchBWT.Elapsed;

                        //long lenghtJPG = VaryQualityLevel(filename, filepath + "\\");
                        List <int> rawList = new List <int>();
                        rawList.Add(l);
                        List <int> rleList = new List <int>();
                        rleList.Add(l2);
                        List <int> lzwList = new List <int>();
                        lzwList.Add(LZWlength);

                        /*List<int> jpegList = new List<int>();
                         * jpegList.Add(Convert.ToInt32(lenghtJPG));*/
                        List <int> BWTList = new List <int>();
                        BWTList.Add(BWTlength);
                        List <int> deflateList = new List <int>();
                        deflateList.Add(Convert.ToInt32(lengthDeflate));
                        chart1.Series[0].Points.DataBindY(rawList);
                        chart1.Series[1].Points.DataBindY(rleList);
                        chart1.Series[2].Points.DataBindY(lzwList);
                        //chart1.Series[3].Points.DataBindY(jpegList);
                        chart1.Series[4].Points.DataBindY(deflateList);
                        chart1.Series[5].Points.DataBindY(BWTList);

                        List <int> timeRLEList = new List <int>();
                        timeRLEList.Add(ts.Seconds / 1000 + ts.Milliseconds);
                        List <int> timeDeflateList = new List <int>();
                        timeDeflateList.Add(ts2.Seconds / 1000 + ts2.Milliseconds);
                        List <int> timeLZWList = new List <int>();
                        timeLZWList.Add(ts1.Seconds / 1000 + ts1.Milliseconds);
                        List <int> timeBWTList = new List <int>();
                        timeBWTList.Add(ts3.Seconds / 1000 + ts1.Milliseconds);
                        chart2.Series[0].Points.DataBindY(timeRLEList);
                        chart2.Series[1].Points.DataBindY(timeLZWList);
                        chart2.Series[3].Points.DataBindY(timeDeflateList);
                        chart2.Series[4].Points.DataBindY(timeBWTList);
                    }
                }
                catch
                {
                    DialogResult rezult = MessageBox.Show("Невозможно открыть выбранный файл",
                                                          "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        /// <inheritdoc />
        public async Task HandleNotificationAsync(MessageReceivedNotification notification, CancellationToken cancellationToken = default)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            if (!(notification.Message is IUserMessage userMessage) ||
                (userMessage.Author is null))
            {
                return;
            }

            if (!(userMessage.Author is IGuildUser author) ||
                (author.Guild is null) ||
                author.IsBot ||
                author.IsWebhook)
            {
                return;
            }

            var argPos = 0;

            if (!userMessage.HasCharPrefix('!', ref argPos) && !userMessage.HasMentionPrefix(DiscordClient.CurrentUser, ref argPos))
            {
                return;
            }

            if (userMessage.Content.Length <= 1)
            {
                return;
            }

            var commandContext = new CommandContext(DiscordClient, userMessage);

            await AuthorizationService.OnAuthenticatedAsync(author);

            IResult commandResult = null;
            var     commandTimer  = Stopwatch.StartNew();

            try
            {
                commandResult = await CommandService.ExecuteAsync(commandContext, argPos, ServiceProvider);
            }
            finally
            {
                commandTimer.Stop();
                var duration = commandTimer.ElapsedMilliseconds;

                if (!(_stats is null) && (commandResult.IsSuccess || !string.Equals(commandResult.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase)))
                {
                    var commandInfo = CommandService.Search(commandContext, argPos).Commands?.FirstOrDefault();
                    if (commandInfo is { } match)
                    {
                        var name = match.Command?.Name.ToLowerInvariant();

                        _stats?.Timer("command_duration_ms", duration,
                                      tags: new[] { $"guild:{commandContext.Guild.Name}", $"success:{commandResult.IsSuccess}", $"command:{name}" });
                    }
                }
            }

            if (!commandResult.IsSuccess)
            {
                var error = $"{commandResult.Error}: {commandResult.ErrorReason}";

                if (string.Equals(commandResult.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase))
                {
                    Log.Error(error);
                }
                else
                {
                    Log.Warning(error);
                }

                if (commandResult.Error == CommandError.Exception)
                {
                    await commandContext.Channel.SendMessageAsync($"Error: {FormatUtilities.SanitizeEveryone(commandResult.ErrorReason)}");
                }
                else
                {
                    await CommandErrorHandler.AssociateError(userMessage, error);
                }
            }

            stopwatch.Stop();
            Log.Information($"Command took {stopwatch.ElapsedMilliseconds}ms to process: {commandContext.Message}");
        }
 private void CheckStopWatch(string message)
 {
     watch.Stop();
     MessageBox.Show(message + " took " + watch.ElapsedMilliseconds.ToString() + "ms");
 }
        /// <summary>
        /// Handle output from API
        /// </summary>
        /// <param name="context"></param>
        private async void PerformOutput(HttpContext context)
        {
            HttpContext.Current.Server.ScriptTimeout = 120; //max script execution time is 2 minutes

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

            //decide correct reponse type
            IOutputProvider outputProvider = null;
            var             filter         = new APIRequestParams();

            //set defaults
            string outputType = "xml";

            filter.DistanceUnit  = DistanceUnit.Miles;
            filter.MaxResults    = 100;
            filter.EnableCaching = true;

            filter.ParseParameters(context);

            //override ?v=2 etc if called via /api/v2/ or /api/v1
            if (APIBehaviourVersion > 0)
            {
                filter.APIVersion = APIBehaviourVersion;
            }
            if (APIBehaviourVersion >= 2)
            {
                filter.Action = DefaultAction;
            }

            if (context.Request.Url.Host.ToLower().StartsWith("api") && filter.APIVersion == null)
            {
                //API version is mandatory for api V2 onwards via api.openchargemap.* hostname
                OutputBadRequestMessage(context, "mandatory API Version not specified in request");
                return;
            }

            if (!String.IsNullOrEmpty(context.Request["output"]))
            {
                outputType = ParseString(context.Request["output"]);
            }
            else
            {
                //new default after API V2 is json instead of XML
                if (filter.APIVersion >= 2)
                {
                    outputType = "json";
                }
            }

            //change defaults and override settings for deprecated api features
            if (filter.APIVersion >= 2)
            {
                //the following output types are deprecated and will default as JSON
                if (outputType == "carwings" || outputType == "rss")
                {
                    OutputBadRequestMessage(context, "specified output type not supported in this API version");
                    return;
                }
            }

            if (IsRequestByRobot)
            {
                OutputBadRequestMessage(context, "API requests by robots are temporarily disabled.", statusCode: 503);
                return;
            }

            //determine output provider
            switch (outputType)
            {
            case "xml":
                outputProvider = new XMLOutputProvider();
                break;

            case "carwings":
            case "rss":
                outputProvider = new RSSOutputProvider();
                if (outputType == "carwings")
                {
                    ((RSSOutputProvider)outputProvider).EnableCarwingsMode = true;
                }
                break;

            case "json":
                outputProvider = new JSONOutputProvider();
                break;

            case "geojson":
                outputProvider = new GeoJSONOutputProvider();
                break;

            case "csv":
                outputProvider = new CSVOutputProvider();
                break;

            case "kml":
                outputProvider = new KMLOutputProvider(KMLOutputProvider.KMLVersion.V2);
                break;

            case "png":
                outputProvider = new ImageOutputProvider();
                break;

            default:
                outputProvider = new XMLOutputProvider();
                break;
            }

            if (outputProvider != null)
            {
                context.Response.ContentEncoding = Encoding.Default;
                context.Response.ContentType     = outputProvider.ContentType;

                if (!(filter.Action == "getcorereferencedata" && String.IsNullOrEmpty(context.Request["SessionToken"])))
                {
                    //by default output is cacheable for 24 hrs, unless requested by a specific user.
                    context.Response.Cache.SetExpires(DateTime.Now.AddDays(1));
                    context.Response.Cache.SetCacheability(HttpCacheability.Public);
                    context.Response.Cache.SetValidUntilExpires(true);
                }

                if (ConfigurationManager.AppSettings["EnableOutputCompression"] == "true")
                {
                    //apply compression if accepted
                    string encodings = context.Request.Headers.Get("Accept-Encoding");

                    if (encodings != null)
                    {
                        encodings = encodings.ToLower();

                        if (encodings.ToLower().Contains("gzip"))
                        {
                            context.Response.Filter = new GZipStream(context.Response.Filter, CompressionLevel.Optimal, false);
                            context.Response.AppendHeader("Content-Encoding", "gzip");
                            //context.Trace.Warn("GZIP Compression on");
                        }
                        else
                        {
                            context.Response.Filter = new DeflateStream(context.Response.Filter, CompressionMode.Compress);
                            context.Response.AppendHeader("Content-Encoding", "deflate");
                            //context.Trace.Warn("Deflate Compression on");
                        }
                    }
                }
                if (filter.Action == "getchargepoints" || filter.Action == "getpoilist")
                {
                    System.Diagnostics.Debug.WriteLine("At getpoilist output: " + stopwatch.ElapsedMilliseconds + "ms");
                    OutputPOIList(outputProvider, context, filter);
                }

                if (filter.Action == "getcompactpoilist")
                {
                    //experimental::
                    OutputCompactPOIList(context, filter);
                }

                if (filter.Action == "getcorereferencedata")
                {
                    OutputCoreReferenceData(outputProvider, context, filter);
                }

                if (filter.Action == "geocode")
                {
                    this.OutputGeocodingResult(outputProvider, context, filter);
                }

                if (filter.Action == "availability")
                {
                    this.OutputAvailabilityResult(outputProvider, context, filter);
                }

                if (filter.Action == "profile.authenticate")
                {
                    this.OutputProfileSignInResult(outputProvider, context, filter);
                }

                if (filter.Action == "refreshmirror")
                {
                    try
                    {
                        var itemsUpdated = await OCM.Core.Data.CacheManager.RefreshCachedData();

                        new JSONOutputProvider().GetOutput(context.Response.OutputStream, new { POICount = itemsUpdated, Status = "OK" }, filter);
                    }
                    catch (Exception exp)
                    {
                        new JSONOutputProvider().GetOutput(context.Response.OutputStream, new { Status = "Error", Message = exp.ToString() }, filter);
                    }
                }

                stopwatch.Stop();
                System.Diagnostics.Debug.WriteLine("Total output time: " + stopwatch.ElapsedMilliseconds + "ms");
            }
        }
Exemple #50
0
        public unsafe void MethodInvocationTiming()
        {
            FooMethods pinvoke_methods;

            foo_get_methods(out pinvoke_methods);

            var p_instance_void = (DV)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.instance_void, typeof(DV));
            var p_instance_int  = (DI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.instance_int, typeof(DI));
            var p_instance_ptr  = (DP)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.instance_ptr, typeof(DP));

            var p_void_1a = (DV1A)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_1_args, typeof(DV1A));
            var p_void_2a = (DV2A)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_2_args, typeof(DV2A));
            var p_void_3a = (DV3A)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_3_args, typeof(DV3A));

            var p_void_1ai = (DV1AI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_1_iargs, typeof(DV1AI));
            var p_void_2ai = (DV2AI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_2_iargs, typeof(DV2AI));
            var p_void_3ai = (DV3AI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_3_iargs, typeof(DV3AI));

            var Object_class = new JniType("java/lang/Object");
            var Object_init  = Object_class.GetConstructor("()V");

            var transfer = JniObjectReferenceOptions.CopyAndDispose;

            var jobj1 = CreateJavaObject(Object_class.NewObject(Object_init, null), transfer);
            var jobj2 = CreateJavaObject(Object_class.NewObject(Object_init, null), transfer);
            var jobj3 = CreateJavaObject(Object_class.NewObject(Object_init, null), transfer);

            var obj1 = new SomeClass();
            var obj2 = new SomeClass();
            var obj3 = new SomeClass();

            var j           = new JavaTiming();
            var m           = new ManagedTiming();
            var comparisons = new[] {
                new {
                    Name    = "static void",
                    Jni     = A(() => JavaTiming.StaticVoidMethod()),
                    Managed = A(() => ManagedTiming.StaticVoidMethod()),
                    Pinvoke = A(() => foo_void_timing()),
                },
                new {
                    Name    = "static int",
                    Jni     = A(() => JavaTiming.StaticIntMethod()),
                    Managed = A(() => ManagedTiming.StaticIntMethod()),
                    Pinvoke = A(() => foo_int_timing()),
                },
                new {
                    Name    = "static object",
                    Jni     = A(() => JavaTiming.StaticObjectMethod()),
                    Managed = A(() => ManagedTiming.StaticObjectMethod()),
                    Pinvoke = A(() => foo_ptr_timing()),
                },
                new {
                    Name    = "virtual void",
                    Jni     = A(() => j.VirtualVoidMethod()),
                    Managed = A(() => m.VirtualVoidMethod()),
                    Pinvoke = A(() => p_instance_void()),
                },
                new {
                    Name    = "virtual int",
                    Jni     = A(() => j.VirtualIntMethod()),
                    Managed = A(() => m.VirtualIntMethod()),
                    Pinvoke = A(() => p_instance_int()),
                },
                new {
                    Name    = "virtual object",
                    Jni     = A(() => j.VirtualObjectMethod()),
                    Managed = A(() => m.VirtualObjectMethod()),
                    Pinvoke = A(() => p_instance_ptr()),
                },
                new {
                    Name    = "final void",
                    Jni     = A(() => j.FinalVoidMethod()),
                    Managed = A(() => m.FinalVoidMethod()),
                    Pinvoke = A(null),
                },
                new {
                    Name    = "final int",
                    Jni     = A(() => j.FinalIntMethod()),
                    Managed = A(() => m.FinalIntMethod()),
                    Pinvoke = A(null),
                },
                new {
                    Name    = "final object",
                    Jni     = A(() => j.FinalObjectMethod()),
                    Managed = A(() => m.FinalObjectMethod()),
                    Pinvoke = A(null),
                },
                new {
                    Name    = "static void o1",
                    Jni     = A(() => JavaTiming.StaticVoidMethod1Args(jobj1)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod1Args(obj1)),
                    Pinvoke = A(() => {
                        // We include timing of the GCHandle manipulation since
                        // a JNI invocation has to do similar work, and pinning
                        // is usually always needed for P/Invokes.
                        GCHandle h1  = GCHandle.Alloc(obj1, GCHandleType.Pinned);
                        IntPtr addr1 = h1.AddrOfPinnedObject();

                        p_void_1a(addr1);

                        h1.Free();
                    }),
                },
                new {
                    Name    = "static void o2",
                    Jni     = A(() => JavaTiming.StaticVoidMethod2Args(jobj1, jobj2)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod2Args(obj1, obj2)),
                    Pinvoke = A(() => {
                        GCHandle h1  = GCHandle.Alloc(obj1, GCHandleType.Pinned),
                        h2           = GCHandle.Alloc(obj2, GCHandleType.Pinned);
                        IntPtr addr1 = h1.AddrOfPinnedObject(),
                        addr2        = h2.AddrOfPinnedObject();

                        p_void_2a(addr1, addr2);

                        h1.Free();
                        h2.Free();
                    }),
                },
                new {
                    Name    = "static void o3",
                    Jni     = A(() => JavaTiming.StaticVoidMethod3Args(jobj1, jobj2, jobj3)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod3Args(obj1, obj2, obj3)),
                    Pinvoke = A(() => {
                        GCHandle h1  = GCHandle.Alloc(obj1, GCHandleType.Pinned),
                        h2           = GCHandle.Alloc(obj2, GCHandleType.Pinned),
                        h3           = GCHandle.Alloc(obj3, GCHandleType.Pinned);
                        IntPtr addr1 = h1.AddrOfPinnedObject(),
                        addr2        = h2.AddrOfPinnedObject(),
                        addr3        = h3.AddrOfPinnedObject();

                        p_void_3a(addr1, addr2, addr3);

                        h1.Free();
                        h2.Free();
                        h3.Free();
                    }),
                },
                new {
                    Name    = "static void i1",
                    Jni     = A(() => JavaTiming.StaticVoidMethod1IArgs(42)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod1IArgs(42)),
                    Pinvoke = A(() => p_void_1ai(42)),
                },
                new {
                    Name    = "static void i2",
                    Jni     = A(() => JavaTiming.StaticVoidMethod2IArgs(42, 42)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod2IArgs(42, 42)),
                    Pinvoke = A(() => p_void_2ai(42, 42)),
                },
                new {
                    Name    = "static void i3",
                    Jni     = A(() => JavaTiming.StaticVoidMethod3IArgs(42, 42, 42)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod3IArgs(42, 42, 42)),
                    Pinvoke = A(() => p_void_3ai(42, 42, 42)),
                },
            };

#if __ANDROID__
            const int count = 1000;
#else   // __ANDROID__
            const int count = 100000;
#endif  // __ANDROID__

            var total = Stopwatch.StartNew();

            foo_init(JniEnvironment.EnvironmentPointer);

            var jniTimes = new long [comparisons.Length];
            foo_get_native_jni_timings(JniEnvironment.EnvironmentPointer, count, JavaTiming.TypeRef.PeerReference.Handle, j.PeerReference.Handle, jniTimes);

            int jniTimeIndex = 0;
            foreach (var c in comparisons)
            {
                var jw = System.Diagnostics.Stopwatch.StartNew();
                for (int i = 0; i < count; ++i)
                {
                    c.Jni();
                }
                jw.Stop();

                var mw = System.Diagnostics.Stopwatch.StartNew();
                for (int i = 0; i < count; ++i)
                {
                    c.Managed();
                }
                mw.Stop();

                System.Diagnostics.Stopwatch pw = null;
                if (c.Pinvoke != null)
                {
                    pw = System.Diagnostics.Stopwatch.StartNew();
                    for (int i = 0; i < count; ++i)
                    {
                        c.Pinvoke();
                    }
                    pw.Stop();
                }

                string message = string.Format("Method Invoke: {0}: JNI is {1}x managed",
                                               c.Name, System.Math.Round(jw.Elapsed.TotalMilliseconds / mw.Elapsed.TotalMilliseconds));
                Console.WriteLine(message);

                var ct = TimeSpan.FromMilliseconds(jniTimes [jniTimeIndex++]);
                Console.WriteLine("\t  C/JNI: {0} ms               | average: {1} ms",
                                  FormatFraction(ct.TotalMilliseconds, 10, 5),
                                  FormatFraction(ct.TotalMilliseconds / count, 12, 5));
                Console.WriteLine("\t    JNI: {0} ms; {1,3}x C/JNI   | average: {2} ms",
                                  FormatFraction(jw.Elapsed.TotalMilliseconds, 10, 5),
                                  ToString(jw.Elapsed, ct),
                                  FormatFraction(jw.Elapsed.TotalMilliseconds / count, 12, 5));
                Console.WriteLine("\tManaged: {0} ms               | average: {1} ms",
                                  FormatFraction(mw.Elapsed.TotalMilliseconds, 10, 5),
                                  FormatFraction(mw.Elapsed.TotalMilliseconds / count, 12, 5));
                if (pw != null)
                {
                    Console.WriteLine("\tPinvoke: {0} ms; {1,3}x managed | average: {2} ms",
                                      FormatFraction(pw.Elapsed.TotalMilliseconds, 10, 5),
                                      ToString(pw.Elapsed, mw.Elapsed),
                                      FormatFraction(pw.Elapsed.TotalMilliseconds / count, 12, 5));
                }
            }

            total.Stop();
            Console.WriteLine("## {0} Timing: {1}", nameof(MethodInvocationTiming), total.Elapsed);
        }
Exemple #51
0
        internal static void ExecuteSQL(NpgsqlConnection connection, NpgsqlTransaction transaction, string sql, InstallSetup setup, List <KeyValuePair <Guid, string> > failedScripts, List <Guid> successOrderScripts)
        {
            if (sql.StartsWith("--##METHODCALL"))
            {
                CallMethod(sql, connection, transaction, setup);
                return;
            }

            //Test for empty statements
            var originalSQL = sql.Trim();

            sql = originalSQL;
            if (string.IsNullOrEmpty(sql))
            {
                return;
            }

            //Test for noop statements (all comments/empty strings)
            var lines = sql.BreakLines().TrimAll();

            lines.RemoveAll(x => x.StartsWith("--"));
            lines.RemoveAll(x => x == "");
            if ([email protected]())
            {
                return;
            }
            lines = sql.BreakLines().TrimAll(); //Reset

            #region Get Script Key
            var isBody = false;
            var key    = Guid.NewGuid();
            var l      = lines.FirstOrDefault(x => x.StartsWith("--MODELID: "));
            if (l != null)
            {
                lines.Remove(l);
                l   = l.Replace("--MODELID:", string.Empty).Trim();
                sql = string.Join("\n", lines.ToArray()); //Remove the model key from the SQL before run
                                                          //if (!Guid.TryParse(l, out key)) key = Guid.NewGuid();
            }
            else
            {
                l = lines.FirstOrDefault(x => x.StartsWith("--MODELID,BODY: "));
                if (l != null)
                {
                    lines.Remove(l);
                    l   = l.Replace("--MODELID,BODY:", string.Empty).Trim();
                    sql = string.Join("\n", lines.ToArray()); //Remove the model key from the SQL before run
                    if (!Guid.TryParse(l, out key))
                    {
                        key = Guid.NewGuid();
                    }
                    else
                    {
                        isBody = true;
                    }
                }
            }
            #endregion
            if (string.IsNullOrEmpty(sql))
            {
                return;
            }

            #region Try to remove objects before creation
            var dropObjectName = string.Empty;
            var dropSQL        = GetSQLDropScript(sql);

            //Add a bit of convenience for dropping DB objects before creation
            if (!string.IsNullOrEmpty(dropSQL))
            {
                try
                {
                    if (!setup.CheckOnly)
                    {
                        var dropCommand = new NpgsqlCommand(dropSQL, connection);
                        dropCommand.Transaction    = transaction;
                        dropCommand.CommandTimeout = 0;
                        DatabaseServer.ExecuteCommand(dropCommand);
                    }
                }
                catch (Exception ex)
                {
                    //Ignore. The scripts should not need this. It has been added for convenience
                }
            }
            #endregion

            var command = new NpgsqlCommand(sql, connection);
            command.Transaction    = transaction;
            command.CommandTimeout = 0;
            try
            {
                if (!setup.CheckOnly)
                {
                    var       debugText = "[" + DateTime.Now.ToString() + "]\r\n";
                    const int MAX_SQL   = 500;
                    var       sqlLength = Math.Min(sql.Length, MAX_SQL);
                    debugText += sql.Substring(0, sqlLength);
                    if (sqlLength == MAX_SQL)
                    {
                        debugText += "...";
                    }
                    debugText += "\r\n\r\n";
                    Log.Verbose(debugText);

                    _timer.Restart();
                    DatabaseServer.ExecuteCommand(command);
                    _timer.Stop();

                    Log.Debug <long, string>("Time:{Elapsed:000} Sql:{sql}", _timer.ElapsedMilliseconds, sql);

                    if (successOrderScripts != null && isBody)
                    {
                        successOrderScripts.Add(key);
                    }
                }
            }
            catch (NpgsqlException sqlexp)
            {
                if (failedScripts != null)
                {
                    //Ignore this error, we will re-process it
                    failedScripts.Add(new KeyValuePair <Guid, string>(key, originalSQL));
                    return;
                }
                else
                {
                    throw new InvalidSQLException(sqlexp.Message, sqlexp)
                          {
                              SQL = sql, FileName = setup.DebugScriptName
                          };
                }
            }
            catch (Exception ex) { throw; }
            finally
            {
                if (command != null)
                {
                    command.Dispose();
                }
            }
        }
Exemple #52
0
        public unsafe int RunVideo(int gap_h, int gap_w, int width, int height, SDLHelper sdlVideo)  //这个是用来渲染整个大画面的
        {
            int          frame_count = 0;
            Produce_data p           = new Produce_data();

            fq              = new FrameQueue();
            p.gap_h         = gap_h;
            p.gap_w         = gap_w;
            p.target_height = height;
            p.target_width  = width;
            IsRun           = true;
            exit_thread     = false;
            pause_thread    = false;
            threadVideo     = Thread.CurrentThread;
            SDL.SDL_Event even    = new SDL.SDL_Event();
            Thread        refresh = new Thread(() => sfp_refresh_thread());
            Thread        produce = new Thread(() => ProduceFrame(ref p));

            refresh.Start();
            produce.Start();
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            try
            {
                for (; ;)
                {
                    //Wait
                    SDL.SDL_WaitEvent(out even);
                    if (even.type == SFM_REFRESH_EVENT)
                    {
                        FrameBuffer fb;
                        // 退出线程
                        if (exit_thread)
                        {
                            break;
                        }
                        // 暂停解析
                        if (pause_thread)
                        {
                            while (pause_thread)
                            {
                                Thread.Sleep(1);
                            }
                        }

                        while (true)
                        {
                            GetFrame(out fb);
                            if (fb == null)
                            {
                                Thread.Sleep(1);
                            }
                            else
                            {
                                fq.Pop();
                                break;
                            }
                            // Console.WriteLine("尚味获取到帧");
                        }
                        frame_count++;
                        //SDL播放YUV数据
                        //var data = fb.outbuffer;


                        int     out_buffer_size = fb.outbuffersize;
                        AVFrame pFrameYUV       = fb.av;
                        sdlVideo.SDL_Display(width * gap_w, height * gap_h, (IntPtr)(pFrameYUV.data[0]), out_buffer_size, pFrameYUV.linesize[0]);


                        //  Console.WriteLine("渲染第" + frame_count.ToString() + "帧");
                        if (frame_count == 1)
                        {
                            stopwatch.Start();
                        }
                        if (frame_count == 1000)
                        {
                            stopwatch.Stop();
                            TimeSpan timespan = stopwatch.Elapsed;
                            Console.WriteLine(timespan.TotalSeconds.ToString());
                            Thread.Sleep(100000);
                        }
                    }
                    else if (even.type == SDL.SDL_EventType.SDL_KEYDOWN)
                    {
                        //Pause
                        if (even.key.keysym.sym == SDL.SDL_Keycode.SDLK_SPACE)
                        {
                            thread_pause = 1 - thread_pause;
                        }
                    }
                    else if (even.type == SDL.SDL_EventType.SDL_QUIT)
                    {
                        thread_exit = 1;
                    }
                    else if (even.type == SFM_BREAK_EVENT)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
            }
            IsRun = false;
            return(0);
        }
Exemple #53
0
        public String GetMultiLUIS(string query)
        {
            //루이스 json 선언
            JObject Luis     = new JObject();
            string  LuisName = "";

            try
            {
                int MAX = MessagesController.LUIS_APP_ID.Count(s => s != null);
                Array.Resize(ref MessagesController.LUIS_APP_ID, MAX);
                Array.Resize(ref MessagesController.LUIS_NM, MAX);

                String[]  returnLuisName = new string[MAX];
                JObject[] Luis_before    = new JObject[MAX];

                List <string[]> textList    = new List <string[]>(MAX);
                String          entitiesSum = "";

                for (int i = 0; i < MAX; i++)
                {
                    //textList.Add(LUIS_APP_ID[i] +"|"+ LUIS_SUBSCRIPTION + "|" + query);
                    textList.Add(new string[] { MessagesController.LUIS_NM[i], MessagesController.LUIS_APP_ID[i], MessagesController.LUIS_SUBSCRIPTION, query });
                }

                //병렬처리 시간 체크
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                Parallel.For(0, MAX, new ParallelOptions {
                    MaxDegreeOfParallelism = MAX
                }, async async =>
                {
                    var task_luis = Task <JObject> .Run(() => GetIntentFromBotLUIS(textList[async][1], textList[async][2], textList[async][3]));

                    try
                    {
                        Task.WaitAll(task_luis);

                        Luis_before[async]    = task_luis.Result;
                        returnLuisName[async] = textList[async][0];
                    }
                    catch (AggregateException e)
                    {
                    }
                });

                watch.Stop();
                //Luis = Luis_before;

                try
                {
                    for (int i = 0; i < MAX; i++)
                    {
                        //엔티티 합치기
                        if ((int)Luis_before[i]["entities"].Count() > 0)
                        {
                            for (int j = 0; j < (int)Luis_before[i]["entities"].Count(); j++)
                            {
                                entitiesSum += (string)Luis_before[i]["entities"][j]["entity"].ToString() + ",";
                            }
                        }
                    }
                }
                catch (IndexOutOfRangeException e)
                {
                    Debug.WriteLine("error = " + e.Message);
                    return("");
                }


                string luisEntities = "";
                string luisType     = "";

                if (!String.IsNullOrEmpty(LuisName))
                {
                    if (Luis != null || Luis.Count > 0)
                    {
                        float luisScore       = (float)Luis["intents"][0]["score"];
                        int   luisEntityCount = (int)Luis["entities"].Count();

                        if (MessagesController.relationList != null)
                        {
                            if (MessagesController.relationList.Count() > 0)
                            {
                                MessagesController.relationList[0].luisScore = (int)Luis["intents"][0]["score"];
                            }
                            else
                            {
                                MessagesController.cacheList.luisScore = Luis["intents"][0]["score"].ToString();
                            }
                        }



                        if (luisScore > Convert.ToDouble(MessagesController.LUIS_SCORE_LIMIT) && luisEntityCount > 0)
                        {
                            for (int i = 0; i < luisEntityCount; i++)
                            {
                                //luisEntities = luisEntities + Luis["entities"][i]["entity"] + ",";
                                luisType     = (string)Luis["entities"][i]["type"];
                                luisType     = Regex.Split(luisType, "::")[1];
                                luisEntities = luisEntities + luisType + ",";
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(luisEntities) || luisEntities.Length > 0)
                    {
                        luisEntities = luisEntities.Substring(0, luisEntities.LastIndexOf(","));
                        luisEntities = Regex.Replace(luisEntities, " ", "");


                        luisEntities = MessagesController.db.SelectArray(luisEntities);

                        if (Luis["intents"] == null)
                        {
                            MessagesController.cacheList.luisIntent = "";
                        }
                        else
                        {
                            MessagesController.cacheList.luisIntent = (string)Luis["intents"][0]["intent"];
                        }

                        MessagesController.cacheList.luisEntities = luisEntities;
                    }

                    //MessagesController.cacheList.luisEntities = LuisName;
                }
                return(LuisName);
            }
            catch (System.Exception e)
            {
                Debug.WriteLine(e.Message);
                return("");
            }
        }
Exemple #54
0
        public static void Benchmark3SavePer(int total_parents, List <long> testTimes, List <long> testTimes2, ref int rowcount, ref int rowcount2)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();
            long cnt1 = 0;

            var people = new EntitySet <PersonWrapped>();

            Parallel.For(1, total_parents + 1, (parentcnt) =>
            {
                using (CEF.NewServiceScope())
                {
                    var parent = CEF.NewObject(new PersonWrapped()
                    {
                        Name = $"NP{parentcnt}", Age = (parentcnt % 60) + 20, Gender = (parentcnt % 2) == 0 ? "F" : "M"
                    });

                    parent.Phones.Add(new Phone()
                    {
                        Number = "888-7777", PhoneTypeID = PhoneType.Mobile
                    });
                    parent.Phones.Add(new Phone()
                    {
                        Number = "777-6666", PhoneTypeID = PhoneType.Work
                    });

                    if ((parentcnt % 12) == 0)
                    {
                        CEF.NewObject(new Phone()
                        {
                            Number = "666-5555", PhoneTypeID = PhoneType.Home
                        });
                    }
                    else
                    {
                        parent.Phones.Add(new Phone()
                        {
                            Number = "777-6666", PhoneTypeID = PhoneType.Home
                        });
                    }

                    Interlocked.Add(ref cnt1, 4);

                    for (int childcnt = 1; childcnt <= (parentcnt % 4); ++childcnt)
                    {
                        var child = CEF.NewObject(new PersonWrapped()
                        {
                            Name   = $"NC{parentcnt}{childcnt}",
                            Age    = parent.Age - 20,
                            Gender = (parentcnt % 2) == 0 ? "F" : "M"
                            ,
                            Phones = new Phone[] { new Phone()
                                                   {
                                                       Number = "999-8888", PhoneTypeID = PhoneType.Mobile
                                                   } }
                        });

                        parent.Kids.Add(child);
                        Interlocked.Add(ref cnt1, 2);
                    }

                    CEF.DBSave();
                }
            });

            rowcount += (int)cnt1;
            testTimes.Add(watch.ElapsedMilliseconds);
            watch.Restart();
            long cnt2 = 0;

            // For purposes of benchmarking, treat this as a completely separate operation
            // For everyone who's a parent of at least 30 yo, if at least 2 children of same sex, remove work phone, increment age

            int?id = null;

            using (var ss = CEF.NewServiceScope())
            {
                var people2 = new EntitySet <Person>().DBRetrieveSummaryForParents(30);

                Parallel.ForEach((from a in people2 let d = a.AsDynamic() where d.MaleChildren > 1 || d.FemaleChildren > 1 select a).ToList(), (p) =>
                {
                    using (CEF.UseServiceScope(ss))
                    {
                        if (!id.HasValue)
                        {
                            id = p.PersonID;
                        }

                        p.AsInfraWrapped().SetValue(nameof(Person.Age), p.Age + 1);

                        var ph2 = new EntitySet <Phone>().DBRetrieveByOwner(p.PersonID, PhoneType.Work).FirstOrDefault();

                        if (ph2 != null)
                        {
                            CEF.DeleteObject(ph2);
                        }

                        p.DBSave();
                        Interlocked.Add(ref cnt2, 2);
                    }
                });

                // Simulate "later heavy read access"...
                for (int c = 0; c < 50000; ++c)
                {
                    var work = new EntitySet <Phone>().DBRetrieveByOwner(c + id.GetValueOrDefault(), PhoneType.Work).FirstOrDefault();

                    if (work != null && work.Number == "123")
                    {
                        MessageBox.Show("Found (should never!)");
                    }
                }
            }

            rowcount2 += (int)cnt2 + 50000;
            watch.Stop();

            testTimes2.Add(watch.ElapsedMilliseconds);
        }
Exemple #55
0
        /// <summary>
        /// Testing simulteneously open files by .NET FileStream
        /// 1MLN - OK
        /// </summary>
        private void TestQuantityOfOpenFiles()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            /*Testing quantity of Files which can be opened by .NET*/
            FileStream fs = null;
            string     pd = @"D:\temp\DBreezeTest\1\";
            Dictionary <int, FileStream> dfs = new Dictionary <int, FileStream>();

            if (System.IO.Directory.Exists(pd))
            {
                System.IO.Directory.Delete(pd, true);
            }

            System.IO.Directory.CreateDirectory(pd);

            int t1 = 0;
            int t2 = 1000000;   //Works well

            //int t2 = 5;

            for (int i = 0; i <= t2; i++)
            {
                try
                {
                    fs = new FileStream(pd + i.ToString(), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);

                    dfs.Add(i, fs);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ERR ENDED WITH {0} open files", i);
                }
            }
            //Console.WriteLine("Done");



            //Console.WriteLine("RW " + t1.ToString());
            //dfs[t1].Write(new byte[] { 1, 2, 3 }, 0, 3);
            //dfs[t1].Flush();
            //byte[] r = new byte[3];
            //dfs[t1].Position = 0;
            //int q = dfs[t1].Read(r, 0, 3);
            //Console.WriteLine(r.ToBytesString(""));

            //dfs[t1].Close();
            //dfs[t1].Dispose();

            //Console.WriteLine("RW " + t2.ToString());
            //dfs[t2].Write(new byte[] { 1, 2, 3 }, 0, 3);
            //dfs[t2].Flush();
            ////byte[] r = new byte[3];
            //dfs[t2].Position = 0;
            //q = dfs[t2].Read(r, 0, 3);
            //Console.WriteLine(r.ToBytesString(""));

            //dfs[t2].Close();
            //dfs[t2].Dispose();


            sw.Stop();
            Console.WriteLine("CREATE FILE DONE " + sw.ElapsedMilliseconds.ToString());

            Console.WriteLine("***************   testing access");

            Random rnd = new Random();
            int    fIn = 0;

            byte[] r = null;
            int    q = 0;

            for (int i = 0; i < 20; i++)
            {
                fIn = rnd.Next(t2 - 1);

                dfs[fIn].Write(new byte[] { 1, 2, 3 }, 0, 3);
                dfs[fIn].Flush();
                r = new byte[3];
                dfs[fIn].Position = 0;
                q = dfs[fIn].Read(r, 0, 3);
                Console.WriteLine("RW: {0}; V: {1}", fIn, r.ToBytesString(""));
            }
        }
Exemple #56
0
        public static void Benchmark1(int total_parents, List <long> testTimes, List <long> testTimes2, ref int rowcount, ref int rowcount2)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();

            using (CEF.NewServiceScope())
            {
                var people = new EntitySet <PersonWrapped>();

                for (int parentcnt = 1; parentcnt <= total_parents; ++parentcnt)
                {
                    var parent = new PersonWrapped()
                    {
                        Name = $"NP{parentcnt}", Age = (parentcnt % 60) + 20, Gender = (parentcnt % 2) == 0 ? "F" : "M"
                    };

                    parent.Phones.Add(new Phone()
                    {
                        Number = "888-7777", PhoneTypeID = PhoneType.Mobile
                    });
                    parent.Phones.Add(new Phone()
                    {
                        Number = "777-6666", PhoneTypeID = PhoneType.Work
                    });

                    if ((parentcnt % 12) == 0)
                    {
                        CEF.NewObject(new Phone()
                        {
                            Number = "666-5555", PhoneTypeID = PhoneType.Home
                        });
                    }
                    else
                    {
                        parent.Phones.Add(new Phone()
                        {
                            Number = "777-6666", PhoneTypeID = PhoneType.Home
                        });
                    }

                    rowcount += 4;

                    for (int childcnt = 1; childcnt <= (parentcnt % 4); ++childcnt)
                    {
                        var child = CEF.NewObject(new PersonWrapped()
                        {
                            Name   = $"NC{parentcnt}{childcnt}",
                            Age    = parent.Age - 20,
                            Gender = (parentcnt % 2) == 0 ? "F" : "M"
                            ,
                            Phones = new Phone[] { new Phone()
                                                   {
                                                       Number = "999-8888", PhoneTypeID = PhoneType.Mobile
                                                   } }
                        });

                        parent.Kids.Add(child);
                        rowcount += 2;
                    }

                    people.Add(parent);
                }

                CEF.DBSave();
            }

            testTimes.Add(watch.ElapsedMilliseconds);
            watch.Restart();

            // For purposes of benchmarking, treat this as a completely separate operation
            using (var ss = CEF.NewServiceScope())
            {
                // For everyone who's a parent of at least 30 yo, if at least 2 children of same sex, remove work phone, increment age
                var people = new EntitySet <Person>().DBRetrieveSummaryForParents(30);

                Parallel.ForEach((from a in people let d = a.AsDynamic() where d.MaleChildren > 1 || d.FemaleChildren > 1 select a).ToList(), (p) =>
                {
                    using (CEF.UseServiceScope(ss))
                    {
                        p.Age += 1;

                        var phones = new EntitySet <Phone>().DBRetrieveByOwner(p.PersonID, PhoneType.Work);

                        if (phones.Any())
                        {
                            CEF.DeleteObject(phones.First());
                        }
                    }
                });

                rowcount2 += CEF.DBSave().Count();
            }

            watch.Stop();
            testTimes2.Add(watch.ElapsedMilliseconds);
        }
Exemple #57
0
        static void Main(string[] args)
        {
            int i, min, max;

            nc = 2;         // количество ядер
            n  = 100000000; // количество элементов в массиве
            A  = new int[n];
            B  = new int[nc];

            Random r = new Random(); // генирируем массив

            for (int j = 0; j < n; j++)
            {
                A[j] = r.Next(100);
            }
            System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch();
            sWatch.Start();  // запуск секундомера
            min = A[0];
            for (i = 1; i < n; i++)
            {
                if (A[i] < min)
                {
                    min = A[i];
                }
            }
            max = A[0];
            for (i = 1; i < n; i++)
            {
                if (A[i] > max)
                {
                    max = A[i];
                }
            }
            Console.WriteLine(min);
            Console.WriteLine(max);
            sWatch.Stop();  // отключение секундомера
            Console.WriteLine("Последовательный алгоритм = {0} мс.", sWatch.ElapsedMilliseconds.ToString());

            // создание массива объектов для хранения параметров
            InputData[] ClArr = new InputData[nc];
            for (i = 0; i < nc; i++)
            {
                ClArr[i] = new InputData();
            }
            // делим количество элементов  в массиве на nc частей
            int step = (Int32)(n / nc);
            // заполняем массив параметров
            int c = -1;

            for (i = 0; i < nc; i++)
            {
                ClArr[i].start = c + 1;
                ClArr[i].stop  = c + step;
                ClArr[i].i     = i;
                c = c + step;
            }
            Dispatcher      d  = new Dispatcher(nc, "Test Pool"); // диспетчер с nc потоками в пуле
            DispatcherQueue dq = new DispatcherQueue("Test Queue", d);
            Port <int>      p  = new Port <int>();

            for (i = 0; i < nc; i++)
            {
                Arbiter.Activate(dq, new Task <InputData, Port <int> >(ClArr[i], p, Mul));
            }
            Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(int[] array)
                                                             {   }));
        }
        public void GetReportAsExcelSpreadsheet(List <int> listOfMeterIDs, MemoryStream ms, CustomerLogic result)
        {
            timeIsolation.IsolationType = SensorAndPaymentReportEngine.TimeIsolations.None;

            // Start diagnostics timer
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            DateTime NowAtDestination = Convert.ToDateTime(this._CustomerConfig.DestinationTimeZoneDisplayName);// DateTime.Now;//Datetime.Now;//DateTime.Now;//Datetime.Now;

            // Now gather and analyze data for the report
            SensorAndPaymentReportEngine.RequiredDataElements requiredDataElements = new SensorAndPaymentReportEngine.RequiredDataElements();
            requiredDataElements.NeedsSensorData            = true;
            requiredDataElements.NeedsPaymentData           = false;
            requiredDataElements.NeedsOverstayData          = false;
            requiredDataElements.NeedsEnforcementActionData = false;
            this._ReportEngine = new SensorAndPaymentReportEngine(this._CustomerConfig, _ReportParams);
            this._ReportEngine.GatherReportData(listOfMeterIDs, requiredDataElements, result);

            OfficeOpenXml.ExcelWorksheet ws = null;

            using (OfficeOpenXml.ExcelPackage pck = new OfficeOpenXml.ExcelPackage())
            {
                // Let's create a report coversheet and overall summary page, with hyperlinks to the other worksheets
                // Create the worksheet
                ws = pck.Workbook.Worksheets.Add("Summary");

                // Render the standard report title lines
                rowIdx = 1; // Excel uses 1-based indexes
                colIdx = 1;
                RenderCommonReportTitle(ws, this._ReportName);

                // Render common report header for enforcement activity restriction filter, but only if its not for all activity
                if (this._ReportParams.ActionTakenRestrictionFilter != SensorAndPaymentReportEngine.ReportableEnforcementActivity.AllActivity)
                {
                    rowIdx++;
                    colIdx = 1;
                    RenderCommonReportFilterHeader_ActionTakenRestrictions(ws);
                }

                // Render common report header for regulated hour restriction filter
                rowIdx++;
                colIdx = 1;
                RenderCommonReportFilterHeader_RegulatedHourRestrictions(ws);

                using (OfficeOpenXml.ExcelRange rng = ws.Cells[2, 1, rowIdx, numColumnsMergedForHeader])
                {
                    rng.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;                 //Set Pattern for the background to Solid
                    rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(207, 221, 237)); //Set color to lighter blue FromArgb(184, 204, 228)
                }

                rowIdx++;
                colIdx = 1;
                int hyperlinkstartRowIdx = rowIdx;

                if (_ReportParams.IncludeMeterSummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Meter Occupancy", "Meter Occupancy summary");
                }
                if (_ReportParams.IncludeSpaceSummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Space Occupancy", "Space Occupancy summary");
                }
                if (_ReportParams.IncludeAreaSummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Area Occupancy", "Area Occupancy summary");
                }
                if (_ReportParams.IncludeDailySummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Daily Occupancy", "Daily Occupancy summary");
                }
                if (_ReportParams.IncludeMonthlySummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Monthly Occupancy", "Monthly Occupancy summary");
                }
                if (_ReportParams.IncludeDetailRecords == true)
                {
                    RenderWorksheetHyperlink(ws, "Details", "Occupancy details");
                }

                rowIdx++;
                rowIdx++;
                colIdx = 1;

                using (OfficeOpenXml.ExcelRange rng = ws.Cells[hyperlinkstartRowIdx, 1, rowIdx, numColumnsMergedForHeader])
                {
                    rng.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.White);
                }


                // Now start the report data summary header
                RenderOverallReportSummary(ws);

                //  --- END OF OVERALL SUMMARY WORKSHEET ---

                // Should we include a worksheet with Meter aggregates?
                if (_ReportParams.IncludeMeterSummary == true)
                {
                    RenderMeterSummaryWorksheet(pck, "Meter Occupancy");
                }

                // Should we include a worksheet with Space aggregates?
                if (_ReportParams.IncludeSpaceSummary == true)
                {
                    RenderSpaceSummaryWorksheet(pck, "Space Occupancy");
                }

                // Should we include a worksheet with Area aggregates?
                if (_ReportParams.IncludeAreaSummary == true)
                {
                    RenderAreaSummaryWorksheet(pck, "Area Occupancy");
                }

                // Should we include a worksheet with Daily aggregates?
                if (_ReportParams.IncludeDailySummary == true)
                {
                    RenderDailySummaryWorksheet(pck, "Daily Occupancy");
                }

                // Should we include a worksheet with Monthly aggregates?
                if (_ReportParams.IncludeDailySummary == true)
                {
                    RenderMonthlySummaryWorksheet(pck, "Monthly Occupancy");
                }


                // Should we include a Details worksheet?
                if (_ReportParams.IncludeDetailRecords == true)
                {
                    // Create the worksheet
                    ws = pck.Workbook.Worksheets.Add("Details");
                    int detailColumnCount = 8;

                    // Render the header row
                    rowIdx = 1; // Excel uses 1-based indexes
                    ws.SetValue(rowIdx, 1, "Space #");
                    ws.SetValue(rowIdx, 2, "Meter #");
                    ws.SetValue(rowIdx, 3, "Area #");
                    ws.SetValue(rowIdx, 4, "Area");
                    ws.SetValue(rowIdx, 5, "Event Start");
                    ws.SetValue(rowIdx, 6, "Event End");
                    ws.SetValue(rowIdx, 7, "Occupied?");
                    ws.SetValue(rowIdx, 8, "Duration");

                    // Format the header row
                    using (OfficeOpenXml.ExcelRange rng = ws.Cells[1, 1, 1, detailColumnCount])
                    {
                        rng.Style.Font.Bold        = true;
                        rng.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;                 //Set Pattern for the background to Solid
                        rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));  //Set color to dark blue
                        rng.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    }

                    // Increment the row index, which will now be the 1st row of our data
                    rowIdx++;

                    #region Populate data for each record

                    foreach (SpaceAsset spaceAsset in this._ReportEngine.ReportDataModel.SpacesIncludedInReport)
                    {
                        List <SensorAndPaymentReportEngine.CommonSensorAndPaymentEvent> spaceRecs = this._ReportEngine.ReportDataModel.FindRecsForBayAndMeter(spaceAsset.SpaceID, spaceAsset.MeterID);
                        foreach (SensorAndPaymentReportEngine.CommonSensorAndPaymentEvent nextEvent in spaceRecs)
                        {
                            // Don't detail this item if its a "dummy" event
                            if (nextEvent.IsDummySensorEvent == true)
                            {
                                continue;
                            }

                            AreaAsset areaAsset = _ReportEngine.GetAreaAsset(spaceAsset.AreaID_PreferLibertyBeforeInternal);

                            // Output row values for data
                            ws.SetValue(rowIdx, 1, spaceAsset.SpaceID);
                            ws.SetValue(rowIdx, 2, spaceAsset.MeterID);

                            if (areaAsset != null)
                            {
                                ws.SetValue(rowIdx, 3, areaAsset.AreaID);
                                ws.SetValue(rowIdx, 4, areaAsset.AreaName);
                            }

                            ws.SetValue(rowIdx, 5, nextEvent.SensorEvent_Start);
                            ws.SetValue(rowIdx, 6, nextEvent.SensorEvent_End);

                            if (nextEvent.SensorEvent_IsOccupied == true)
                            {
                                ws.SetValue(rowIdx, 7, "Y");
                            }
                            else
                            {
                                ws.SetValue(rowIdx, 7, "N");
                            }

                            ws.SetValue(rowIdx, 8, FormatTimeSpanAsHoursMinutesAndSeconds(nextEvent.SensorEvent_Duration));

                            // Increment the row index, which will now be the next row of our data
                            rowIdx++;

                            // Is there a child "repeat" event also?
                            if (nextEvent.RepeatSensorEvents != null)
                            {
                                foreach (SensorAndPaymentReportEngine.CommonSensorAndPaymentEvent repeatEvent in nextEvent.RepeatSensorEvents)
                                {
                                    ws.SetValue(rowIdx, 1, spaceAsset.SpaceID);
                                    ws.SetValue(rowIdx, 2, spaceAsset.MeterID);

                                    if (areaAsset != null)
                                    {
                                        ws.SetValue(rowIdx, 3, areaAsset.AreaID);
                                        ws.SetValue(rowIdx, 4, areaAsset.AreaName);
                                    }

                                    ws.SetValue(rowIdx, 5, repeatEvent.SensorEvent_Start);
                                    ws.SetValue(rowIdx, 6, repeatEvent.SensorEvent_End);

                                    if (repeatEvent.SensorEvent_IsOccupied == true)
                                    {
                                        ws.SetValue(rowIdx, 7, "Y");
                                    }
                                    else
                                    {
                                        ws.SetValue(rowIdx, 7, "N");
                                    }

                                    ws.SetValue(rowIdx, 8, FormatTimeSpanAsHoursMinutesAndSeconds(repeatEvent.SensorEvent_Duration));

                                    // Increment the row index, which will now be the next row of our data
                                    rowIdx++;
                                }
                            }
                        }
                    }
                    #endregion

                    // We will add autofilters to our headers so user can sort the columns easier
                    using (OfficeOpenXml.ExcelRange rng = ws.Cells[1, 1, rowIdx, detailColumnCount])
                    {
                        rng.AutoFilter = true;
                    }

                    // Apply formatting to the columns as appropriate (Starting row is 2 (first row of data), and ending row is the current rowIdx value)

                    ApplyNumberStyleToColumn(ws, 1, 2, rowIdx, "########0", ExcelHorizontalAlignment.Left);
                    ApplyNumberStyleToColumn(ws, 2, 2, rowIdx, "########0", ExcelHorizontalAlignment.Left);
                    ApplyNumberStyleToColumn(ws, 3, 2, rowIdx, "########0", ExcelHorizontalAlignment.Left);

                    ApplyNumberStyleToColumn(ws, 5, 2, rowIdx, "yyyy-mm-dd hh:mm:ss tt", ExcelHorizontalAlignment.Right);
                    ApplyNumberStyleToColumn(ws, 6, 2, rowIdx, "yyyy-mm-dd hh:mm:ss tt", ExcelHorizontalAlignment.Right);

                    ApplyNumberStyleToColumn(ws, 7, 2, rowIdx, "@", ExcelHorizontalAlignment.Right); // String value, right-aligned
                    ApplyNumberStyleToColumn(ws, 8, 2, rowIdx, "@", ExcelHorizontalAlignment.Right); // String value, right-aligned

                    // And now lets size the columns
                    for (int autoSizeColIdx = 1; autoSizeColIdx <= detailColumnCount; autoSizeColIdx++)
                    {
                        using (OfficeOpenXml.ExcelRange col = ws.Cells[1, autoSizeColIdx, rowIdx, autoSizeColIdx])
                        {
                            col.AutoFitColumns();
                        }
                    }
                }


                // All cells in spreadsheet are populated now, so render (save the file) to a memory stream
                byte[] bytes = pck.GetAsByteArray();
                ms.Write(bytes, 0, bytes.Length);
            }

            // Stop diagnostics timer
            sw.Stop();
            System.Diagnostics.Debug.WriteLine(this._ReportName + " generation took: " + sw.Elapsed.ToString());
        }
        /// <summary>
        /// Builds the solution.
        /// </summary>
        /// <param name="placeholderDriver">The PlaceHolder driver.</param>
        /// <param name="jobNodes">The job nodes.</param>
        /// <param name="driverNodes">The driver nodes.</param>
        /// <returns></returns>
        public virtual Solution BuildSolution(Driver placeholderDriver, IList <INode> jobNodes, IList <DriverNode> driverNodes)
        {
            var stopWatch = new System.Diagnostics.Stopwatch();

            stopWatch.Start();

            int  iterationsSinceBestResult = 0;
            int  totalIterations           = 0;
            bool stopping = false;

            Solution bestSolution = null;
            var      subSolutions = new List <Solution>();

            // Define iteration
            Action <int, ParallelLoopState> iterationAction = (i, loopState) =>
            {
                var solution = ProcessDrivers(driverNodes, placeholderDriver, jobNodes);

                _rwLock.EnterWriteLock();

                try
                {
                    totalIterations++;
                    iterationsSinceBestResult++;
                    subSolutions.Add(solution);

                    // Update progress
                    OnProgressEvent(
                        new ProgressEventArgs()
                    {
                        PrimaryTotal = MaxIterations,
                        PrimaryValue = totalIterations
                    });

                    var oldBest = bestSolution;

                    bestSolution = bestSolution == null ? solution : _routeService.GetBestSolution(bestSolution, solution);

                    if (bestSolution != oldBest)
                    {
                        _currentBestSolution      = bestSolution;
                        iterationsSinceBestResult = 0;
                    }

                    // Check exit criteria
                    if ((loopState == null || !loopState.IsStopped) && iterationsSinceBestResult > MaxIterationSinceBestResult)
                    {
                        _logger.Info("Max iterations since best result reached ({0})", MaxIterationSinceBestResult);
                        stopping = true;
                    }

                    if ((loopState == null || !loopState.IsStopped) && stopWatch.ElapsedMilliseconds > MaxExecutionTime)
                    {
                        _logger.Info("Max execution time {0} reached", MaxExecutionTime);
                        stopping = true;
                    }

                    if (_isCancelling)
                    {
                        stopping = true;
                    }

                    if (stopping)
                    {
                        if (loopState != null)
                        {
                            loopState.Stop();
                        }
                    }
                }
                finally
                {
                    _rwLock.ExitWriteLock();
                }

                // Update Pheromone Matrix
                if (!stopping && PheromoneUpdateFrequency > 0 && i > 0 && i % PheromoneUpdateFrequency == 0)
                {
                    List <Solution> subResultCopy = null;

                    _rwLock.EnterWriteLock();
                    {
                        subResultCopy = subSolutions.ToList();
                        subSolutions.Clear();
                    }
                    _rwLock.ExitWriteLock();

                    foreach (var subSolution in subResultCopy)
                    {
                        _pheromoneMatrix.UpdatePheromoneMatrix(subSolution);
                    }
                }
            };

            // Run iterations
            //if (EnableParallelism)
            if (false)      // ajh ajh
            {
                Parallel.For(0, MaxIterations, iterationAction);
            }
            else
            {
                for (var i = 0; i < MaxIterations; i++)
                {
                    iterationAction(i, null);

                    if (stopping)
                    {
                        break;
                    }
                }
            }

            stopWatch.Stop();

            return(bestSolution);
        }
Exemple #60
0
        private void btnCrcFile_Click(object sender, EventArgs e)
        {
            btnFile_Click(btnCrcFile, new EventArgs());
            Application.DoEvents();
            int times = 1000;

            byte[]       bs = File.ReadAllBytes(txtCrcFile.Text);
            FileStream   fs = File.OpenRead(txtCrcFile.Text);
            MemoryStream ms = new MemoryStream(bs);

            byte[] res = null;
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            Crc16 crc16 = Crc16.Create();

            watch.Start();
            for (int i = 0; i < times; i++)
            {
                res = crc16.ComputeHash(bs);
            }
            watch.Stop();
            lab16B.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            watch.Restart();
            for (int i = 0; i < times; i++)
            {
                res = crc16.ComputeHash(fs);
            }
            watch.Stop();
            lab16S.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            watch.Restart();
            for (int i = 0; i < times; i++)
            {
                res = crc16.ComputeHash(ms);
            }
            watch.Stop();
            lab16M.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            Crc32 crc32 = Crc32.Create();

            watch.Start();
            for (int i = 0; i < times; i++)
            {
                res = crc32.ComputeHash(bs);
            }
            watch.Stop();
            lab32B.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            watch.Restart();
            for (int i = 0; i < times; i++)
            {
                res = crc32.ComputeHash(fs);
            }
            watch.Stop();
            lab32S.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            watch.Restart();
            for (int i = 0; i < times; i++)
            {
                res = crc32.ComputeHash(ms);
            }
            watch.Stop();
            lab32M.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
        }