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; }
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(); }
public TraceAttributeContext(string traceId, string methodId, string parentMethodId) { TraceId = traceId; MethodId = methodId; ParentMethodId = parentMethodId; Stopwatch = Stopwatch.StartNew(); }
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); } }
public FlockGame() { kdBuildTimer = new System.Diagnostics.Stopwatch(); updateTimer = new System.Diagnostics.Stopwatch(); anchorFlock = new Flock(); }
/// <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 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 IEnumerable<long> GetPrimeFactors(long product) { var sw = new Stopwatch(); sw.Start(); var initialProduct = product; var primeFactors = new List<long>(); while (product != 1) { long factor = 1; for (long potentialFactor = 2; potentialFactor <= product; potentialFactor++) { if (primeChecker.IsPrime(potentialFactor) && (product % potentialFactor == 0)) { factor = potentialFactor; Trace.WriteLine(string.Format("Factor: {0}", factor)); primeFactors.Add(factor); break; } } product = product / factor; if(primeChecker.IsPrime(product)) { primeFactors.Add(product); break; } } sw.Stop(); Trace.WriteLine(string.Format("PrimeFactorGenerator2 - time taken to find factors for {0}: {1} ticks", initialProduct, sw.ElapsedTicks)); return primeFactors; }
public void Inverse() { var stopWatch = new Stopwatch(); stopWatch.Start(); var csgA = new CSG.CSG(); csgA.Construct(A.GetComponent<MeshFilter>().sharedMesh, A.transform, 0); var substract = csgA.Inverse(); var newMesh = substract.ToMesh(); Result = new GameObject("Inverse"); var defObj = Result.AddComponent<DefaultObject>(); var meshFilter = Result.AddComponent<MeshFilter>(); meshFilter.sharedMesh = newMesh; var renderer = Result.AddComponent<MeshRenderer>(); renderer.sharedMaterial = new Material(A.GetComponent<MeshRenderer>().sharedMaterial); if (DeleteOriginal) { Object.DestroyImmediate(A); } stopWatch.Stop(); defObj.GenerationTimeMS = stopWatch.ElapsedMilliseconds; }
//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); }
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 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(); }
//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); }
/// <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; }
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); } } }
public TemplateGenerationMetadata GenerateMetadata() { var timer = new Stopwatch(); timer.Start(); // load the templates we'll be generating into a state storage collection var templateData = CreateTemplateData(); foreach (var template in templateData.Templates) { HashSet<string> fieldKeys = GetBaseFieldSet(); // get fields on base type fieldKeys.Add(template.TypeName); // member names cannot be the same as their enclosing type so we add the type name to the fields collection foreach (var baseTemplate in template.Template.AllNonstandardBaseTemplates) // similarly names can't be the same as any of their base templates' names (this would cause an incompletely implemented interface) { if (templateData.Contains(baseTemplate.TemplateId)) { fieldKeys.Add(templateData[baseTemplate.TemplateId].TypeName); } else fieldKeys.Add(baseTemplate.Name.AsIdentifier()); // NOTE: you could break this if you have a base template called Foo and a field called Foo that IS NOT on the Foo template (but why would you have that?) } // generate item properties foreach (var field in template.Template.Fields) { if (_templateInputProvider.IsFieldIncluded(field.Id)) // query the template input provider and make sure the field is included { string propertyName = field.Name.AsNovelIdentifier(fieldKeys); var fieldInfo = new FieldPropertyInfo(field); fieldInfo.FieldPropertyName = propertyName; fieldInfo.SearchFieldName = _indexFieldNameTranslator.GetIndexFieldName(field.Name); fieldInfo.FieldType = _fieldMappingProvider.GetFieldType(field); if (fieldInfo.FieldType == null) { Log.Warn("Synthesis: Field type resolution for " + field.Template.Name + "::" + field.Name + " failed; no mapping found for field type " + field.Type, this); continue; // skip adding the field for generation } // record usage of the property name fieldKeys.Add(propertyName); // add the field to the metadata template.FieldsToGenerate.Add(fieldInfo); } } // generates interfaces to represent the Sitecore template inheritance hierarchy TemplateInfo baseInterface = GenerateInheritedInterfaces(template.Template, templateData); if (baseInterface != null) template.InterfacesImplemented.Add(baseInterface); } timer.Stop(); Log.Info(string.Format("Synthesis: Generated metadata for {0} concrete templates and {1} interface templates in {2} ms", templateData.Templates.Count, templateData.Interfaces.Count, timer.ElapsedMilliseconds), this); return templateData; }
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"); } }
public async Task<ActionResult> DailyMaintenance(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 daily maintenance. stopWatch.Reset(); stopWatch.Start(); // Run daily maintenance tasks. await this.doctrineShipsServices.DailyMaintenance(); // Stop the clock. stopWatch.Stop(); logger.LogMessage("Daily Maintenance Successful, Time Taken: " + stopWatch.Elapsed, 2, "Message", MethodBase.GetCurrentMethod().Name); return Content("Daily Maintenance Successful, Time Taken: " + stopWatch.Elapsed); } else { logger.LogMessage("Daily Maintenance Failed, Invalid Key: " + cleanKey, 1, "Message", MethodBase.GetCurrentMethod().Name); return Content("Daily Maintenance Failed, Invalid Key"); } }
// public methods public void Opened() { _stopwatch = Stopwatch.StartNew(); _appPackage.CurrentNumberOfOpenConnections.Increment(); _serverPackage.CurrentNumberOfOpenConnections.Increment(); }
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); }
public object Run() { Stopwatch = Stopwatch.StartNew(); object result = RunSolution(); Stopwatch.Stop(); return result; }
public async Task Invoke(HttpContext context) { var sw = new Stopwatch(); sw.Start(); using (var memoryStream = new MemoryStream()) { var bodyStream = context.Response.Body; context.Response.Body = memoryStream; await _next(context); var isHtml = context.Response.ContentType?.ToLower().Contains("text/html"); if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault()) { memoryStream.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(memoryStream)) { var responseBody = await streamReader.ReadToEndAsync(); //C# 6 DEMO var newFooter = string.Format($"<footer><div id='process'>Page processed in {sw.ElapsedMilliseconds} milliseconds.</div>"); responseBody = responseBody.Replace("<footer>", newFooter); context.Response.Headers.Add("X-ElapsedTime", new[] { sw.ElapsedMilliseconds.ToString() }); using (var amendedBody = new MemoryStream()) using (var streamWriter = new StreamWriter(amendedBody)) { streamWriter.Write(responseBody); amendedBody.Seek(0, SeekOrigin.Begin); await amendedBody.CopyToAsync(bodyStream); } } } } }
public ISearchResult Search(string query) { var timer = new Stopwatch(); timer.Start(); var directory = FSDirectory.Open(new DirectoryInfo(path)); var analyzer = new StandardAnalyzer(Version.LUCENE_29); var searcher = new IndexSearcher(directory, true); var queryParser = new QueryParser(Version.LUCENE_29, "text", analyzer); var result = searcher.Search(queryParser.Parse(query), 20); var docs = (from scoreDoc in result.scoreDocs let doc = searcher.Doc(scoreDoc.doc) let fields = new Dictionary<string, string> { { "title", doc.Get("title") }, { "text", doc.Get("text") } } select new LuceneDocument { Id = scoreDoc.doc.ToString(), Fields = fields }).ToList(); var ret = new SearchResult { Query = query, Total = result.totalHits, Documents = docs, Source = Name }; searcher.Close(); directory.Close(); timer.Stop(); ret.Duration = (decimal) timer.Elapsed.TotalSeconds; return ret; }
/// <summary> /// new DeltaTime object /// </summary> public DeltaTime() { m_manualDt = false; m_dt = 0; m_timer = new Stopwatch(); m_timer.Start(); }
public SocketTestClient( ITestOutputHelper log, string server, int port, int iterations, string message, Stopwatch timeProgramStart) { _log = log; _server = server; _port = port; _endpoint = new DnsEndPoint(server, _port); _sendString = message; _sendBuffer = Encoding.UTF8.GetBytes(_sendString); _bufferLen = _sendBuffer.Length; _recvBuffer = new byte[_bufferLen]; _timeProgramStart = timeProgramStart; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // on Unix, socket will be created in Socket.ConnectAsync { _timeInit.Start(); _s = new Socket(SocketType.Stream, ProtocolType.Tcp); _timeInit.Stop(); } _iterations = iterations; }
public void PerformanceRemoveRoom_With5000RemoveCommands_With10000BunniesIn5000Rooms() { for (int i = 0; i < 5000; i++) { this.BunnyWarCollection.AddRoom(i); } for (int i = 0; i < 10000; i++) { this.BunnyWarCollection.AddBunny(i.ToString(), i % 5, i / 2); } //Arrange var count = 5000; var roomsCount = 5000; //Act Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i < roomsCount; i++) { this.BunnyWarCollection.Remove(i); Assert.AreEqual(--count, this.BunnyWarCollection.RoomCount, "Incorrect count of rooms after removal!"); } timer.Stop(); Assert.IsTrue(timer.ElapsedMilliseconds < 400); }
/// <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; }
public void Configuration(IAppBuilder app) { app.Run(context => { Stopwatch stopWatch = new Stopwatch(); Trace.WriteLine("Received client call. Starting stop watch now."); stopWatch.Start(); context.Request.CallCancelled.Register(() => { stopWatch.Stop(); Trace.WriteLine(string.Format("Cancellation token triggered. Elapsed time : {0}. Test should succeed", stopWatch.Elapsed)); NotificationServer.NotifyClient(); }); int retryCount = 0; while (retryCount < 3) { Thread.CurrentThread.Join(5 * 1000); if (context.Request.CallCancelled.IsCancellationRequested) { break; } retryCount++; } return context.Response.WriteAsync("FAILURE"); }); }
// Add all cubes to a ModelVisual3D, reuse geometry but create new visual for each cube - this is slow /* GeometryModel3D AddGeometrySeparate(IEnumerable<Point3D> centers, double L) { var mv = new ModelVisual3D(); var cubit = new CubeVisual3D { SideLength = L * 0.95, Fill = Brushes.Gold }; var cuboidGeometry = cubit.Model.Geometry as MeshGeometry3D; var r = new Random(); foreach (var center in centers) { var tg = new Transform3DGroup(); tg.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), (r.NextDouble() - 0.5) * 10))); tg.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), (r.NextDouble() - 0.5) * 10))); tg.Children.Add(new TranslateTransform3D(center.ToVector3D())); var c = new ModelVisual3D { Content = new GeometryModel3D { Geometry = cuboidGeometry, Material = cubit.Material, Transform = tg } }; mv.Children.Add(c); } return mv; }*/ // All cubes in one GeometryModel - much faster GeometryModel3D AddGeometry(IEnumerable<Point3D> centers, double L) { var w = new Stopwatch(); w.Start(); /* var geometry = new MeshGeometry3D(); foreach (var center in centers) { MeshGeometryHelper.AddBox(geometry,center, L, L, L); } */ var builder = new MeshBuilder(); foreach (var center in centers) { builder.AddBox(center, L, L, L); } var geometry = builder.ToMesh(); geometry.Freeze(); Trace.WriteLine(Level + ": " + w.ElapsedMilliseconds + " ms"); var mv = new GeometryModel3D { Geometry = geometry, Material = MaterialHelper.CreateMaterial(Brushes.Gold) }; TriangleCount = geometry.TriangleIndices.Count / 3; return mv; }
/// <summary> /// Prueft die history, ob die jeweilige Bewegung ausgelöst wird oder nicht. /// </summary> /// <param name="history">The history.</param> /// <returns></returns> public ErkennerStatus Pruefe(Skeleton[] history) { var headY = history.Select(x => x.Joints[JointType.Head].Position.Y); var leftFootY = history.Select(x => x.Joints[JointType.FootLeft].Position.Y); bool unten = (headY.Max() - headY.First() > 0.15) && (leftFootY.First() - leftFootY.Min()) < 0.02; bool oben = (headY.First() - headY.Min() > 0.1) && (leftFootY.Max()-leftFootY.First()) < 0.02; if (Blocked) { if (BlockStopwatch.ElapsedMilliseconds > 700) { Blocked = false; BlockStopwatch = null; } } if (!Blocked) { if (_geduckt && oben) { _geduckt = false; MotionFunctions.SendAction(MotionFunctions.DownUp()); return ErkennerStatus.NichtAktiv; } if (!_geduckt && unten) { _geduckt = true; MotionFunctions.SendAction(MotionFunctions.DownDown()); return ErkennerStatus.Aktiv; } } return _geduckt ? ErkennerStatus.Aktiv : ErkennerStatus.NichtAktiv; }
public Action1000(ActionGetter actionGetter) : base(1000, actionGetter) { responsePack = new ResponsePack(); _watch = new Stopwatch(); _versionsNotSupport = new List<string>(); }
/// <summary> /// 计时器开始 /// </summary> /// <returns></returns> public static Diagnostics.Stopwatch TimerStart() { var watch = new Diagnostics.Stopwatch(); watch.Reset(); watch.Start(); return(watch); }
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); } } }
private void beginCalculation(int k, int numTotalStores) { previousPrinted = 0; AddStatus(Environment.NewLine + "Calculating " + k + " store solutions..."); if (k > 2) { AddStatus(Environment.NewLine + " Millions of solutions checked: "); } stopWatch = new System.Diagnostics.Stopwatch(); //shortcount = 0; longcount = 0; // Added to this method by CAC, 7/6/15 to fix a bug related to the report. matches = new List <FinalMatch>(); matchesfoundcount = 0; stopWatch.Start(); SetProgressBar(numTotalStores); running = true; stopAlgorithmEarly = false; }
static void Main(string[] args) { Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); int tryNumber = 500000; var ValueFunction = new ValueFunction(); for (int i = 0; i < tryNumber; i++) { var Blackjack = new BlackjackPlay(i); Blackjack.InitDeal(); Blackjack.GameStart(); ValueFunction.NewEpisode(Blackjack.ResultFrag(), Blackjack.PlayerCards(), Blackjack.DealerCards()); } ValueFunction.Evaluation(); sw.Stop(); Console.WriteLine(sw.Elapsed); }
public void TestWritingPbfFile() { var methodName = MethodBase.GetCurrentMethod().Name; Utils.ShowStarting(methodName); if (!File.Exists(TestRawFilePath)) { Assert.Ignore(@"Skipping test {0} since file not found: {1}", methodName, TestRawFilePath); } Console.WriteLine(@"Writing..."); var sw = new System.Diagnostics.Stopwatch(); sw.Start(); var outputFilePath = PbfLcMsRun.GetPbfFileName(TestRawFilePath); var pbf = new PbfLcMsRun(TestRawFilePath, null, outputFilePath); Console.WriteLine(@"Done. {0:f4} sec", sw.Elapsed.TotalSeconds); }
public Game() { System.Console.WriteLine("--- AlmostTetris v0.1 ---"); grid = new int[GamePanel.GAME_HEIGHT, GamePanel.GAME_WIDTH]; nbBlocs = 7; nbShapes = 7; fillShapes(); buildBlocs(); randGen = new Random(); dropTimer = new System.Diagnostics.Stopwatch(); comboTimer = new System.Diagnostics.Stopwatch(); replayMode = false; saveReplay = true; replaySave = new ReplaySave("c:\\test.trs"); restart(); }
//HillClimber improve the evaluation so MAXIMIZE! public Dictionary <int, StructuredAlias> RandomRestartHillClimber(StructuredAlias realMap, EvaluateNode Eval) { AliasChallengePriorityQueue = new SimplePriorityQueue <Dictionary <int, StructuredAlias> >(); iterationRandomRestart = 0; graphPlot.Clear(); ParameterManager pMan = ParameterManager.Instance; System.Diagnostics.Stopwatch sWatch = StopwatchProxy.Instance.Stopwatch; sWatch.Stop(); sWatch.Reset(); sWatch.Start(); int totalIterations = 0; while (iterationRandomRestart < maxIterations) { try { if (sWatch.ElapsedMilliseconds > pMan.timeCap * 1000f && pMan.timeCap >= 0) { throw new Exception("Time cap elapsed.\n"); } AliasChallengePriorityQueue.Enqueue(HillClimber(realMap, Eval), -(float)returnEval); } catch (Exception e) { ErrorManager.ManageError(ErrorManager.Error.SOFT_ERROR, e.Message + sWatch.ElapsedMilliseconds / 1000f + "s #iteration: " + iterationRandomRestart + " (" + totalIterations + returnIter + ")." + SaveAliasChallengeOptimization()); sWatch.Stop(); sWatch.Reset(); return(AliasChallengePriorityQueue.Dequeue()); } totalIterations += returnIter; iterationRandomRestart++; } GeneratorUIManager.Instance.showMessageDialogBox("F= " + Mathf.Abs(AliasChallengePriorityQueue.GetPriority(AliasChallengePriorityQueue.First)) + "\nExecution time: " + sWatch.ElapsedMilliseconds / 1000f + "s #iteration: " + iterationRandomRestart + " (" + maxIterations * pMan.hillClimberNumBatch + ")." + SaveAliasChallengeOptimization()); sWatch.Stop(); sWatch.Reset(); return(AliasChallengePriorityQueue.Dequeue()); }
IEnumerator Optimize () { Dictionary<int, long> Times = new Dictionary<int, long>(); Dictionary<int, int> Iterations = new Dictionary<int, int>(); Diagnostics.Stopwatch stopwatch = new Diagnostics.Stopwatch(); for (int i = 1; i < 25; i++) { gridCount = 0; grid = null; newGrid = null; subdivGrid = null; newLevel = i; stopwatch.Start(); yield return StartCoroutine(CreateGrid()); stopwatch.Stop(); Iterations.Add(i, iterationCount); Times.Add(i, stopwatch.ElapsedMilliseconds); stopwatch.Reset(); } float bestTime = Times[1]; int bestIterations = Iterations[1]; int bestTimeIterations = 0; int bestIterationsIterations = 0; string times = ""; string iters = ""; for (int t = 1; t < Times.Count; t++) { times = string.Concat(times, "Subdivision level: ", t.ToString(), ". Time spent: ", (Times[t]/1000f).ToString(), " seconds\n"); iters = string.Concat(iters, "Subdivision level: ", t.ToString(), ". Iteration count: ", Iterations[t].ToString(),"\n"); if ((Times[t]/1000f) < bestTime) { bestTime = Times[t]/1000f; bestTimeIterations = t; } if (Iterations[t] < bestIterations) { bestIterations = Iterations[t]; bestIterationsIterations = t; } } Debug.Log("Best time is "+bestTime + " seconds at subdivision level "+bestTimeIterations); Debug.Log("Best iteration count is "+bestIterations + " at subdivision level "+bestIterationsIterations); Debug.Log(iters); Debug.Log(times); }
private void b_triangulation(object sender, RoutedEventArgs e) { if (debug) { Console.WriteLine("Начало триангуляции:"); } System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); //Запуск процесса триангуляции Triangulation.Triangulation triangulation = new Triangulation.Triangulation(Points); sw.Stop(); Console.WriteLine("Time Taken-->{0}", sw.ElapsedMilliseconds); Triangles = triangulation.triangles; pointsBitmap = Helper.BitmapImage2Bitmap(sourceBitmapPicture); //Расскрашивание треугольников int indexCol = Triangles.Count; for (int y = 0; y < indexCol; y++) { Triangles[y].color = pointsBitmap.GetPixel((int)Triangles[y].Centroid.x, (int)Triangles[y].Centroid.y); } //Отрисовка триангуляции на экран var graphics = Graphics.FromImage(pointsBitmap); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; for (int s = 0; s < Triangles.Count; s++) { graphics.FillPolygon(new System.Drawing.SolidBrush(Triangles[s].color), new PointF[] { new PointF((float)Triangles[s].points[0].x, (float)Triangles[s].points[0].y), new PointF((float)Triangles[s].points[1].x, (float)Triangles[s].points[1].y), new PointF((float)Triangles[s].points[2].x, (float)Triangles[s].points[2].y) }); } sourceImg.Source = Helper.Bitmap2BitmapImage(pointsBitmap); }
/// <summary> /// Waits until the provided element is not visible. /// </summary> /// <param name="element">The element to check</param> /// <param name="waitMilliseconds">The amount of time to wait. If not provided the system will wait the default value (2 seconds).</param> /// <remarks>The default wait time could be overridden.</remarks> /// <returns>Task for executing the operation.</returns> public Task WaitTillNotVisible(PageElement element, int waitMilliseconds = -1) { return(Task.Run(() => { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); if (waitMilliseconds == -1) { waitMilliseconds = DefaultWait; } IWebElement webElement = null; try { webElement = driver.FindElement(OpenQA.Selenium.By.CssSelector(element.Selector)); } catch (NoSuchElementException) { } var hidden = false; Stopwatch sw2 = new Stopwatch(); sw2.Start(); while (sw2.ElapsedMilliseconds < waitMilliseconds && hidden == false) { if (webElement == null) { try { webElement = driver.FindElement(OpenQA.Selenium.By.CssSelector(element.Selector)); } catch (NoSuchElementException) { } } if (webElement != null && !webElement.Displayed) { hidden = true; } } if (!hidden) { throw new Exception("The web element (" + element.Description + " - " + element.Selector + ") was not hidden."); } sw.Stop(); System.Diagnostics.Trace.WriteLine(" WaitTillNotVisible (" + sw.ElapsedMilliseconds.ToString() + "ms): " + element.Selector); })); }
public void InitDeviceResources() { Bitmap txb = new Bitmap(1, 1); using (Graphics g = Graphics.FromImage(txb)) g.Clear(Color.White); Bitmap hcursorb = new Bitmap(32, 32); using (Graphics g = Graphics.FromImage(hcursorb)) Cursors.NoMoveHoriz.Draw(g, new Rectangle(0, 0, 32, 32)); MakeGray(hcursorb); Bitmap vcursorb = new Bitmap(32, 32); using (Graphics g = Graphics.FromImage(vcursorb)) Cursors.NoMoveVert.Draw(g, new Rectangle(0, 0, 32, 32)); MakeGray(vcursorb); Bitmap hvcursorb = new Bitmap(32, 32); using (Graphics g = Graphics.FromImage(hvcursorb)) Cursors.NoMove2D.Draw(g, new Rectangle(0, 0, 32, 32)); MakeGray(hvcursorb); sprite = new Sprite(_device); sprite2 = new Sprite(_device); tx_ellipses = new Dictionary <EllipseKey, TextureExt>(); tx = Methods.Drawing.TextureCreator.FromBitmap(_device, txb); hcursor = Methods.Drawing.TextureCreator.FromBitmap(_device, hcursorb); vcursor = Methods.Drawing.TextureCreator.FromBitmap(_device, vcursorb); hvcursor = Methods.Drawing.TextureCreator.FromBitmap(_device, hvcursorb); FontDX = new Font(_device, FontDescription); FontDX_Bold = new Font(_device, FontDescription_Bold); FPS_Clock = Stopwatch.StartNew(); }
private void OnMouseUp(InputEventArgs e) { var thread = new Thread(new ThreadStart(() => { Log.Debug(string.Format("Windows.Recording::OnMouseUp::begin")); var re = new RecordEvent(); re.Button = e.Button; var a = new GetElement { DisplayName = e.Element.Id + "-" + e.Element.Name }; var sw = new System.Diagnostics.Stopwatch(); sw.Start(); WindowsSelector sel = null; // sel = new WindowsSelector(e.Element.rawElement, null, true); sel = new WindowsSelector(e.Element.rawElement, null, false); if (sel.Count < 2) { return; } if (sel == null) { return; } a.Selector = sel.ToString(); re.UIElement = e.Element; re.Element = e.Element; re.Selector = sel; re.X = e.X; re.Y = e.Y; Log.Debug(e.Element.SupportInput + " / " + e.Element.ControlType); re.a = new GetElementResult(a); re.SupportInput = e.Element.SupportInput; Log.Debug(string.Format("Windows.Recording::OnMouseUp::end {0:mm\\:ss\\.fff}", sw.Elapsed)); OnUserAction?.Invoke(this, re); })); thread.IsBackground = true; thread.Start(); }
public static void Main1() { var watch = new System.Diagnostics.Stopwatch(); float TIMESTEP = 250; // 250 MILISECONDS = 0.25 SEC float simtime, elaps_time; simtime = 0; elaps_time = 0; bool isRunning = true; globalmembers.gl.sim_spd = 100; globalmembers.model_config(); while (isRunning) { watch.Start(); while (elaps_time < TIMESTEP) { if (globalmembers.gl.run_count < globalmembers.gl.sim_spd) { globalmembers.Simulation(); } elaps_time = watch.ElapsedMilliseconds; } watch.Stop(); simtime += (elaps_time * globalmembers.gl.run_count) / 1000; // sec Console.Write("\r"); //Console.Write(simtime); /// Console.Write(globalmembers.hdr[1].p); globalmembers.gl.run_count = 0; watch.Reset(); elaps_time = 0; } }
private void button2_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = "C:/mygit/BCIT_Lab/Lab_1"; openFileDialog.Filter = "txt files (*.txt)|*.txt"; openFileDialog.FilterIndex = 1; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); string path = openFileDialog.FileName; System.IO.StreamReader sr = new System.IO.StreamReader(path); string text = sr.ReadToEnd(); char[] spl = { ' ', ',', '.', ';', ':', '(', ')', '\n' }; string[] words_str = text.Split(spl); for (int j = 0; j < words_str.Length; j++) { if ((String.Compare(words_str[j], "\0") != 0) && (String.Compare(words_str[j], "\n") != 0) && (String.Compare(words_str[j], "\r") != 0)) { if (!list.Contains(words_str[j])) { list.Add(words_str[j]); } } } stopWatch.Stop(); TimeSpan time = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", time.Hours, time.Minutes, time.Seconds, time.Milliseconds / 10); textBox1.Text = elapsedTime; add_to_list_box(list); } }
public void Double() { var srcList = new List <Point2 <double> >(4); var dstList = new List <Point2 <double> >(4); srcList.Add(new Point2 <double>(-152, 394)); srcList.Add(new Point2 <double>(218, 521)); srcList.Add(new Point2 <double>(223, -331)); srcList.Add(new Point2 <double>(-163, -219)); dstList.Add(new Point2 <double>(-666, 431)); dstList.Add(new Point2 <double>(500, 300)); dstList.Add(new Point2 <double>(480, -308)); dstList.Add(new Point2 <double>(-580, -280)); var stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); var h**o = Homography.Find(srcList, dstList); var json = JsonSerializer.Serialize(h**o); try { var homo2 = JsonSerializer.Deserialize <HomographyMatrix <double> >(json); Assert.IsTrue(h**o.Elements.Count == homo2?.Elements.Count); for (int i = 0; i < h**o.Elements.Count; i++) { Assert.IsTrue(Math.Abs(h**o.Elements[i] - homo2.Elements[i]) < 0.001); } } catch (Exception e) { Console.WriteLine(e); throw; } }
/// <summary> /// Verifies whether the provided element has the specified text. /// </summary> /// <param name="element">Element to check.</param> /// <param name="text">Text the element should contain.</param> public void ElementHasText(PageElement element, string text) { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); IWebElement webElement = driver.FindElement(OpenQA.Selenium.By.CssSelector(element.Selector)); if (webElement == null) { throw new Exception($"The web element ({element.Description} - {element.Selector}) was not found."); } else { var foundText = webElement.Text; if (foundText.CompareTo(text) != 0) { throw new Exception($"The web element ({element.Description} - {element.Selector}) did not have text '{text}' it was '{foundText}'."); } } sw.Stop(); System.Diagnostics.Trace.WriteLine($" ElementHasText ({sw.ElapsedMilliseconds.ToString()}ms): {text}"); }
protected void btnStart_OnClick(object sender, EventArgs e) { TokenSource = new CancellationTokenSource(); _watch = Di.Stopwatch.StartNew(); _taskCouter = 64; Di.Trace.WriteLine(string.Format("{0} Starting test. Worker type: {1}, workers count: {2}, clientType: {3}", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture), "Pure Async", 64, "Async TcpClient")); TokenSource = new CancellationTokenSource(); int delay; if (!int.TryParse(txtDelay.Text, out delay)) { delay = 20; } for (int i = 0; i < 64; i++) { var i1 = i; HostingEnvironment.QueueBackgroundWorkItem(ct => RunCommunicationInTaskAsync(TokenSource.Token, delay, i1)); } }
private void cm_BbackgroundWorker_DoWork(object sender, DoWorkEventArgs eventArgs) { BackgroundWorker _worker = sender as BackgroundWorker; Debug.Assert(_worker != null); Debug.Assert(eventArgs.Argument is LocalOperation); LocalOperation _requestedOperation = (LocalOperation)eventArgs.Argument; try { // Get the BackgroundWorker that raised this event. Stopwatch _StopWatch = new System.Diagnostics.Stopwatch(); _requestedOperation.ConnectReq(); _StopWatch.Start(); while (!_worker.CancellationPending) { _requestedOperation.DoOperation(); if (_requestedOperation.Delay > 20) { System.Threading.Thread.Sleep(_requestedOperation.Delay); } if (_StopWatch.ElapsedMilliseconds > 1000) { _worker.ReportProgress(0, _requestedOperation.GetOperationsResult()); _StopWatch.Reset(); _StopWatch.Start(); } } _requestedOperation.DisReq(); eventArgs.Cancel = true; eventArgs.Result = null; } catch (Exception ex) { eventArgs.Result = ex; eventArgs.Cancel = false; _requestedOperation.DisReq(); } }
public override bool FileExists(string file_path) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); if (!this.IsConnected) { throw new InvalidOperationException("The SSH session is not connected."); } SshCommand ls_cmd = SshClient.RunCommand("stat " + file_path); sw.Stop(); if (!string.IsNullOrEmpty(ls_cmd.Result)) { Debug("stat {0} returned {1} in {2} ms.", file_path, ls_cmd.Result, sw.ElapsedMilliseconds); return(true); } else { Debug("stat {0} returned {1} in {2} ms.", file_path, ls_cmd.Error, sw.ElapsedMilliseconds); return(false); } }
/// <summary> /// Verifies the style attribute of the provided element /// matches the regular expression provided. /// </summary> /// <param name="element">The element to check.</param> /// <param name="styleRegEx">The regular expression to use.</param> public void ElementStyleMatches(PageElement element, string styleRegEx) { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); IWebElement webElement = driver.FindElement(OpenQA.Selenium.By.CssSelector(element.Selector)); if (webElement == null) { throw new Exception("The web element (" + element.Description + " - " + element.Selector + ") was not found."); } else { string styleFound = webElement.GetAttribute("style"); if (!System.Text.RegularExpressions.Regex.Match(styleFound, styleRegEx).Success) { throw new Exception("The web element (" + element.Description + " - " + element.Selector + ") did not have a style that matched '" + styleRegEx + "' it was '" + styleFound + "'."); } } sw.Stop(); System.Diagnostics.Trace.WriteLine(" ElementStyleMatches (" + sw.ElapsedMilliseconds.ToString() + "ms): " + styleRegEx); }
/// <summary> /// Verifies the provided page element has a titla attribute /// matching the value provided. /// </summary> /// <param name="element">The element to check.</param> /// <param name="title">The value the element should have for the title attribute.</param> public void ElementHasTitle(PageElement element, string title) { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); IWebElement webElement = driver.FindElement(OpenQA.Selenium.By.CssSelector(element.Selector)); if (webElement == null) { throw new Exception("The web element (" + element.Description + " - " + element.Selector + ") was not found."); } else { string titleFound = webElement.GetAttribute("title"); if (titleFound != title) { throw new Exception("The web element (" + element.Description + " - " + element.Selector + ") did not have text '" + title + "' it was '" + titleFound + "'."); } } sw.Stop(); System.Diagnostics.Trace.WriteLine(" ElementHasTitle (" + sw.ElapsedMilliseconds.ToString() + "ms): " + title); }
static void Build(BuildTarget target, string path, BuildOptions opts = BuildOptions.None) { var watch = new System.Diagnostics.Stopwatch(); watch.Start(); ClearAllLuaFiles(); CopyLuaFilesToRes(); AssetBundleGen.NamedAssetBundleName(); AssetBundleTool.CreateAndroidAssetBundle(); CSObjectWrapEditor.Generator.ClearAll(); CSObjectWrapEditor.Generator.GenAll(); // SGK.Database.LoadConfigFromServer(); // SGK.CharacterConfig.GenerateBattleCharacterConfig(); /* * string UNITY_CACHE_SERVER = System.Environment.GetEnvironmentVariable("UNITY_CACHE_SERVER"); * if (!string.IsNullOrEmpty(UNITY_CACHE_SERVER)) { * EditorPrefs.SetBool("CacheServerEnabled", false); * EditorPrefs.SetInt("CacheServerMode", 1); * EditorPrefs.SetString("CacheServerIPAddress", UNITY_CACHE_SERVER); * } */ string ANDROID_HOME = System.Environment.GetEnvironmentVariable("ANDROID_HOME"); if (!string.IsNullOrEmpty(ANDROID_HOME)) { EditorPrefs.SetString("AndroidSdkRoot", System.Environment.GetEnvironmentVariable("ANDROID_HOME")); } BuildPipeline.BuildPlayer(scenes, path, target, opts); watch.Stop(); UnityEngine.Debug.Log(string.Format("build package dela time {0}ms, {1}s, {2}min", watch.ElapsedMilliseconds, watch.ElapsedMilliseconds / 1000, watch.ElapsedMilliseconds / 1000 / 60)); }
public void Select_Speed() { var dbFactory = new DbFactory(SqlClientFactory.Instance); var cmdGenerator = new DbCommandBuilder(dbFactory); Query q = new Query("test"); q.Condition = createTestQuery(); q.Fields = new QField[] { "name", "age" }; // SELECT TEST var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); for (int i = 0; i < 10000; i++) { IDbCommand cmd = cmdGenerator.GetSelectCommand(q); } stopwatch.Stop(); Console.WriteLine("Speedtest for select command generation (10000 times): {0}", stopwatch.Elapsed); }
public static void TestCompileFac() { string eval = System.IO.File.ReadAllText(Program.GetFilePath("Eval.asm")); string entry = "main"; CodeResult result; try { #if DEBUG System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); #endif result = CellMachineAssembler.Assemble(eval, entry); #if DEBUG sw.Stop(); Console.Error.WriteLine("!Code assembled in {0}", sw.Elapsed); #endif } catch (Exception e) { Console.WriteLine("Failed to assemble: {0}", e.Message); #if DEBUG Console.WriteLine("Stack trace:"); Console.WriteLine(e.StackTrace); #endif return; } List <Cell> args = new List <Cell>(); args.Add(new Cell(10)); Machine machine = new Machine(result, args); while (machine.Finished == false) { machine.Step(); if (false) { machine.PrintState(); } } }
/// <summary> /// Initializes the script engine (once per thread). /// </summary> /// <returns> An initialized script engine. </returns> private ScriptEngine InitializeScriptEngine() { // Initialize the script engine. var engine = new ScriptEngine(); #if DEBUG engine.EnableDebugging = true; #endif engine.OptimizationStarted += (sender, e) => { parseTime = timer.Elapsed.TotalMilliseconds; timer.Restart(); }; engine.CodeGenerationStarted += (sender, e) => { optimizationTime = timer.Elapsed.TotalMilliseconds; timer.Restart(); }; engine.ExecutionStarted += (sender, e) => { codeGenerationTime = timer.Elapsed.TotalMilliseconds; timer.Restart(); }; // Call the user-supplied init callback. if (initCallback != null) { timer = Stopwatch.StartNew(); this.initCallback(engine); } return(engine); }
static void Mul(InputData data, Port <int> resp) { int i, j; System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch(); sWatch.Start(); for (i = data.start; i <= data.stop; i++) { for (j = i; i <= data.stop; i++) { if (a[j] > a[j + 1]) { int b = a[j]; //change for elements a[j] = a[j + 1]; a[j + 1] = b; } } } sWatch.Stop(); resp.Post(1); Console.WriteLine("Поток № {0}: Параллельный алгоритм = {1} мс.", Thread.CurrentThread.ManagedThreadId, sWatch.ElapsedMilliseconds.ToString()); }
static void Main(string[] args) { Console.WriteLine("Listans längd:"); int length = int.Parse(Console.ReadLine()); int range = 10; int[] list = new int[length]; Random random = new Random(); System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); for (int i = 0; i < list.Length; i++) { list[i] = random.Next(range); } timer.Start(); Bubblesort(list); timer.Stop(); Console.WriteLine("Time elapsed: " + timer.ElapsedMilliseconds + " millisekunder"); }