public void Parse() { var subject = new PatternParser(new LiteralParser()); const string Source = @"Hi, {Name, select, male={guy} female={gal}}, you have {count, plural, zero {no friends}, other {# friends} }"; Benchmark.Start("First run (warm-up)", this.outputHelper); subject.Parse(new StringBuilder(Source)); Benchmark.End(this.outputHelper); Benchmark.Start("Next one (warmed up)", this.outputHelper); var actual = subject.Parse(new StringBuilder(Source)); Benchmark.End(this.outputHelper); Assert.Equal(2, actual.Count()); var formatterParam = actual.First(); Assert.Equal("Name", formatterParam.Variable); Assert.Equal("select", formatterParam.FormatterName); Assert.Equal("male={guy} female={gal}", formatterParam.FormatterArguments); formatterParam = actual.ElementAt(1); Assert.Equal("count", formatterParam.Variable); Assert.Equal("plural", formatterParam.FormatterName); Assert.Equal("zero {no friends}, other {# friends}", formatterParam.FormatterArguments); }
protected async System.Threading.Tasks.Task <bool> LintBuildSelection(bool isBuildingSolution) { try { Benchmark.Start(); if (!LinterService.IsLinterEnabled) { return(false); } UIHierarchyItem[] selectedItems = BuildSelectedItems.Get(isBuildingSolution); Dictionary <string, string> fileToProjectMap; string[] files = WebLinterPackage.Settings.UseTsConfig ? TsconfigLocations.FindPathsFromSelectedItems(selectedItems, out fileToProjectMap) : LintFileLocations.FindPathsFromSelectedItems(selectedItems, out fileToProjectMap); if (!files.Any()) { return(false); } return(await LinterService.Lint(showErrorList : true, fixErrors : false, callSync : true, fileNames : files, clearAllErrors : true, fileToProjectMap)); } catch (Exception ex) { Logger.LogAndWarn(ex); Linter.Server.Down(); return(true); // Return value is true if we have VS errors } finally { Benchmark.End(); } }
public void Parse(string source, string expectedKey, string expectedFormat, string expectedArgs) { var literalParserMock = new Mock <ILiteralParser>(); var sb = new StringBuilder(source); literalParserMock.Setup(x => x.ParseLiterals(sb)); literalParserMock.Setup(x => x.ParseLiterals(sb)) .Returns(new[] { new Literal(0, source.Length, 1, 1, new StringBuilder(source)) }); var subject = new PatternParser(literalParserMock.Object); // Warm up (JIT) Benchmark.Start("Parsing formatter patterns (first time before JIT)", this.outputHelper); subject.Parse(sb); Benchmark.End(this.outputHelper); Benchmark.Start("Parsing formatter patterns (after warm-up)", this.outputHelper); var actual = subject.Parse(sb); Benchmark.End(this.outputHelper); Assert.Equal(1, actual.Count()); var first = actual.First(); Assert.Equal(expectedKey, first.Variable); Assert.Equal(expectedFormat, first.FormatterName); Assert.Equal(expectedArgs, first.FormatterArguments); }
public void ValidIdentifier_DumpsResult() { using (Benchmark.Start("Benchmark")) { } var res = Benchmark.Dump(); Assert.IsNotNull(res); }
public void NullIdentifier_ThrowsArgumentNullException() { Assert.Throws <ArgumentNullException>(() => { using (Benchmark.Start(null)) { } }); }
static void Main(string[] args) { Benchmark benchmark = new Benchmark(); benchmark.Register(typeof(Program).Assembly); benchmark.Start(80, true); }
/// <summary> /// 像素方式访问 /// </summary> private void TestBlendImageCode2() { var bmp = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + "2016-01-12-15h.png"); Benchmark.Start(); LockBitmap lockBitmap = new LockBitmap(bmp); lockBitmap.LockBits(); Color compareClr = Color.FromArgb(255, 255, 255, 255); for (int y = 0; y < lockBitmap.Height; y++) { for (int x = 0; x < lockBitmap.Width; x++) { if (lockBitmap.GetPixel(x, y) == compareClr) { lockBitmap.SetPixel(x, y, Color.Red); } } } lockBitmap.UnlockBits(); Benchmark.End(); double seconds = Benchmark.GetSeconds(); bmp.Dispose(); }
static void Main(string[] args) { Benchmark.Begin += (name, id) => { using (ConsoleUtil.Color(fg: ConsoleColor.Green)) Console.WriteLine("{0}:{1}->{2}", id, name, DateTime.Now); }; Benchmark.End += (name, id, elapse) => { using (ConsoleUtil.Color(fg: ConsoleColor.Green)) Console.WriteLine("{0}:{1}->{2}ms, {3}", id, name, elapse, DateTime.Now); }; using (Benchmark.Start("*")) { try { List <IStatement> ast; using (Benchmark.Start("parse")) ast = TSql.ParseFile("Test.sql").ToList(); using (Benchmark.Start("analyze")) Analyze(ast); } catch (Exception e) { using (ConsoleUtil.Color(ConsoleColor.Red)) Console.WriteLine(e.Message); } } Console.WriteLine("Press any key to quit..."); Console.ReadKey(true); }
public void SimulationStep(int subStep) { if (subStep == 1000) { // This is the 'late update data' phase return; } else if (!isRunning) { isRunning = true; try { // On failure, don't try to activate benchmark on each step benchmark.Start(); Log.Info("Benchmarking started."); } catch { } } if ((SimulationManager.instance.m_currentFrameIndex & 0xFFF) == 0xFFF) { benchmark.MakeSnapshot(); } }
private void OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e) { using (var benchmark = Benchmark.Start()) { IBaseEntity entity = e.Entity as IBaseEntity; var entityFormatters = Container.TryGetAll <IEntityFormatter>(); if (entity != null) { foreach (var formatter in entityFormatters) { if (formatter.OnLoad(e.Entity.GetType(), entity)) { ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntry(e.Entity).AcceptChanges(); } } entity.OnLoad(this); } benchmark.Stop(); if (LoggingEnabled) { Logger.Info(Logger.Completed(benchmark.TotalTime, true, "Entity Loaded: {0}".FormatString(e.Entity.GetType().Name)), RepositoryConstants.RepositoryComponent); } } }
public void FormatMessage_using_real_parser_and_library_mock(string source, string expected) { var mockLibary = new Mock <IFormatterLibrary>(); var dummyFormatter = new Mock <IFormatter>(); var subject = new MessageFormatter( new PatternParser(new LiteralParser()), mockLibary.Object, false); var args = new Dictionary <string, object?>(); args.Add("name", "Jeff"); dummyFormatter.Setup(x => x.Format("en", It.IsAny <FormatterRequest>(), args, "Jeff", subject)) .Returns("Jeff"); mockLibary.Setup(x => x.GetFormatter(It.IsAny <FormatterRequest>())).Returns(dummyFormatter.Object); // Warm up Benchmark.Start("Warm-up", this.outputHelper); subject.FormatMessage(source, args); Benchmark.End(this.outputHelper); Benchmark.Start("Aaaand a few after warm-up", this.outputHelper); for (int i = 0; i < 1000; i++) { subject.FormatMessage(source, args); } Benchmark.End(this.outputHelper); Assert.Equal(expected, subject.FormatMessage(source, args)); }
public void ParseExtensions(string args, string extension, string value, int expectedIndex) { var subject = new BaseFormatterImpl(); int index; var req = new FormatterRequest(new Literal(1, 1, 1, 1, new StringBuilder()), string.Empty, null, args); // Warmup subject.ParseExtensions(req, out index); Benchmark.Start("Parsing extensions a few times (warmed up)", this.outputHelper); for (int i = 0; i < 1000; i++) { subject.ParseExtensions(req, out index); } Benchmark.End(this.outputHelper); var actual = subject.ParseExtensions(req, out index); Assert.NotEmpty(actual); var first = actual.First(); Assert.Equal(extension, first.Extension); Assert.Equal(value, first.Value); Assert.Equal(expectedIndex, index); }
public void BuildRain(RainMethod pm, Benchmark bench = null) { Benchmark.Start(bench, "Rain"); // etc if (pm == RainMethod.Equal) { BuildRainByEqual(); } else if (pm == RainMethod.Noise) { BuildRainByNoise(); } else if (pm == RainMethod.Wind) { WindSpawn ws = WindSpawn.TradeLinear; WindRainType rt = WindRainType.HeatBasedContinuous; WindEvaporationType et = WindEvaporationType.WaterAndHeat; WindTurnType wt = WindTurnType.TerrainBased; BuildRainByWind(1000, ws, rt, et, wt, bench); MapUtil.TransformMapMinMax(ref Rain, MapUtil.dNormalize); } if (bench != null) { bench.EndBenchmark("Rain"); } }
public void ParseKeyedBlocks(string args, string[] keys, string[] values) { var subject = new BaseFormatterImpl(); var req = new FormatterRequest(new Literal(1, 1, 1, 1, new StringBuilder()), string.Empty, null, args); // Warm-up subject.ParseKeyedBlocks(req, 0); Benchmark.Start("Parsing keyed blocks..", this.outputHelper); for (int i = 0; i < 10000; i++) { subject.ParseKeyedBlocks(req, 0); } Benchmark.End(this.outputHelper); var actual = subject.ParseKeyedBlocks(req, 0); Assert.Equal(keys.Length, actual.Count()); this.outputHelper.WriteLine("Input: " + args); this.outputHelper.WriteLine("-----"); for (int index = 0; index < actual.ToArray().Length; index++) { var keyedBlock = actual.ToArray()[index]; var expectedKey = keys[index]; var expectedValue = values[index]; Assert.Equal(expectedKey, keyedBlock.Key); Assert.Equal(expectedValue, keyedBlock.BlockText); this.outputHelper.WriteLine("Key: " + keyedBlock.Key); this.outputHelper.WriteLine("Block: " + keyedBlock.BlockText); } }
private void InternalRun() { Benchmark.Start(TaskDescription); var components = FindConnectedComponents().ToList(); Console.WriteLine("Sizes of the largest components are: {0}", string.Join(",", components.Select(l => l.Count).OrderByDescending(l => l).Take(5))); Console.WriteLine("Total size of components is: {0}", components.Select(c => c.Count).Sum()); Benchmark.Finish(); }
static void Main(string[] args) { Benchmark.Begin += (name, id) => { using (ConsoleUtil.Color(fg: ConsoleColor.Green)) Console.WriteLine("{0}:{1}->{2}", id, name, DateTime.Now); }; Benchmark.End += (name, id, elapse) => { using (ConsoleUtil.Color(fg: ConsoleColor.Green)) Console.WriteLine("{0}:{1}->{2}ms, {3}", id, name, elapse, DateTime.Now); }; using (Benchmark.Start("total")) { const string testFilePath = @"Test.txt"; string text; using (Benchmark.Start("io")) text = File.ReadAllText(testFilePath); try { var tokens = new Token[0]; Console.WriteLine("=== token ==="); using (Benchmark.Start("lexer")) { using (Benchmark.Start("lex")) tokens = text.Lex().ToArray(); using (Benchmark.Start("print")) foreach (var token in tokens) { Console.WriteLine(token); } } Console.WriteLine("=== statements ==="); using (Benchmark.Start("parser")) { IEnumerable <IStatement> statements; using (Benchmark.Start("parse")) statements = tokens.Parse().ToArray(); using (Benchmark.Start("print")) statements.Write(Console.Out); } } catch (Exception ex) { using (ConsoleUtil.Color(fg: ConsoleColor.Red)) Console.WriteLine(ex.Message); } } Console.ReadKey(true); }
private void b_start_Click(object sender, EventArgs e) { var cards = new List <Card>(); b_start.Enabled = false; Benchmark.Start(); var nudCnt = nud_city.Value + 1; //Алгоритм рандомной генерации уменьшает города на 1 if (nudCnt == 1) { var card1 = new Card { CityFrom = "Мельбурн", CityTo = "Кельн" }; var card2 = new Card { CityFrom = "Москва", CityTo = "Париж" }; var card3 = new Card { CityFrom = "Кельн", CityTo = "Москва" }; cards = new List <Card> { card1, card2, card3 }; } else { cards = TestListAdd((int)nudCnt); } var sorted = arrange(cards); //Алгоритм сортировки входящего набора карточек Benchmark.End(); MessageBox.Show(@"Прошло: " + Benchmark.GetSeconds() + @" секунд.", @"Тестируем"); if (nudCnt > 20) { MessageBox.Show(@"Карточки отсортированы"); } else { var report = @"Данные по путешествию."; foreach (Card crd in sorted) { report += Environment.NewLine + " " + crd.CityFrom + " -> " + crd.CityTo; } MessageBox.Show(report); } b_start.Enabled = true; }
public async Task PerformTask() { long[] array = await FileReader.ReadLongArray(@"Assets/" + FileName); if (array != null) { data = new HashSet <long>(array); Benchmark.Start(TaskDescription); Console.WriteLine(string.Format("Amount of unique 2-sum pairs: {0}", ComputeTwoSum(array))); Benchmark.Finish(); } }
/// <summary> /// Performs all tasks for Week 1 "Algorithms: Design and Analysis, Part 1" course /// </summary> public async Task PerformTask() { int[] array = await FileReader.ReadIntegerArray(@"Assets/" + FileName); if (array != null) { Benchmark.Start(TaskDescription); long inversions = GetInversionsCount(array, 0, array.Length - 1); Benchmark.Finish(); Console.WriteLine(string.Format("Amount of inversions: {0}", inversions)); } }
public void WithDiferentIdentifiers_DumpMultipleResults() { using (Benchmark.Start("Benchmark")) { } using (Benchmark.Start("Another benchmark")) { } var res = Benchmark.Dump(); var results = res.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length; Assert.AreEqual(2, results); }
public async Task PerformTask() { int[] array = await FileReader.ReadIntegerArray(@"Assets/" + FileName); if (array != null) { Queue <int> values = new Queue <int>(array); Benchmark.Start(TaskDescription); long result = ComputeMedian(values); Console.WriteLine(string.Format("Median: {0}", result)); Benchmark.Finish(); } }
static void Main(string[] args) { if (args != null && args.Length > 0) { Setting.SERVER_HOST = args[0]; } Benchmark benchmark = new Benchmark(); benchmark.Register(typeof(Program).Assembly); benchmark.Start(); Console.WriteLine($"rpc benchmark server [{Setting.SERVER_HOST}]"); Console.Read(); }
public void FormatMessage(string source, Dictionary <string, object> args, string expected) { var subject = new MessageFormatter(false); // Warmup subject.FormatMessage(source, args); Benchmark.Start("Formatting", this.outputHelper); string result = subject.FormatMessage(source, args); Benchmark.End(this.outputHelper); Assert.Equal(expected, result); this.outputHelper.WriteLine(result); }
///------------------------------------------------------------------------------------------------- /// <summary> /// Build Model from types. /// </summary> /// /// <param name="folderPath"> /// The folder path to save. /// </param> /// <param name="list"> /// The list. /// </param> ///------------------------------------------------------------------------------------------------- public static void Save(string folderPath, IReadOnlyList <Type> list) { bool localizationEnabled = false; var config = ConfigManager.GetConfig(); if (config != null) { localizationEnabled = config.Application.LocalizationEnabled; } folderPath = Path.Combine(folderPath, "models"); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } Array languages = localizationEnabled ? Enum.GetValues(typeof(LanguageCode)) : new[] { (byte)LanguageCode.English }; foreach (var value in languages) { var language = ((LanguageCode)value); string fileName = language == LanguageCode.English ? Path.Combine(folderPath, "models.js") : Path.Combine(folderPath, "models." + language.ToString("G").ToLowerInvariant() + ".js"); if (!File.Exists(fileName)) { Logger.Info(Logger.Executing("Building Knockout Model: {0}".FormatString(fileName))); using (Benchmark benchmark = Benchmark.Start()) { try { CultureInfo currentCulture = new CultureInfo(LocalizationManager.GetLanguageLCID(language)); using (StreamWriter stream = new StreamWriter(fileName, false, Encoding.UTF8)) { stream.Write(Build(list, currentCulture)); } Logger.Info(Logger.Completed(benchmark.TotalTime, true, "Building Knockout Model: {0}".FormatString(fileName)), KOConstants.KnockoutBuilderComponent); } catch (Exception exception) { Logger.Error(Logger.Failed(benchmark.TotalTime, "Building Knockout Model: {0}".FormatString(fileName)), KOConstants.KnockoutBuilderComponent); Logger.Error(exception, KOConstants.KnockoutBuilderComponent); } } } } }
static void Main(string[] args) { Benchmark.Begin += (name, id) => { using (ConsoleUtil.Color(fg: ConsoleColor.Green)) Console.WriteLine("{0}:{1}->{2}", id, name, DateTime.Now); }; Benchmark.End += (name, id, elapse) => { using (ConsoleUtil.Color(fg: ConsoleColor.Green)) Console.WriteLine("{0}:{1}->{2}ms, {3}", id, name, elapse, DateTime.Now); }; using (Benchmark.Start("*")) { try { List <IStatement> ast; using (Benchmark.Start("parse")) ast = TSql.ParseFile("Test.sql").ToList(); using (HashAlgorithm hash = MD5.Create()) using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { using (Benchmark.Start("format")) { ast.Write(writer); writer.Flush(); } stream.Seek(0, SeekOrigin.Begin); byte[] hashBytes; using (Benchmark.Start("hash")) hashBytes = hash.ComputeHash(stream); Console.WriteLine("Hash is '{0}'", Format(hashBytes)); } } catch (Exception e) { using (ConsoleUtil.Color(ConsoleColor.Red)) Console.WriteLine(e.Message); } } Console.WriteLine("Press any key to quit..."); Console.ReadKey(true); }
///------------------------------------------------------------------------------------------------- /// <summary> /// Gets the Entity Repository. /// </summary> /// /// <typeparam name="TEntity"> /// Type of the entity. /// </typeparam> /// /// <returns> /// Entity Repository. /// </returns> ///------------------------------------------------------------------------------------------------- public IRepository <TEntity> Get <TEntity>() where TEntity : class, IBaseEntity { using (var benchmark = Benchmark.Start()) { Repository <TEntity> repository = new Repository <TEntity>(this); benchmark.Stop(); if (LoggingEnabled) { Logger.Info(Logger.Completed(benchmark.TotalTime, true, "Get Repository: {0}".FormatString(typeof(TEntity).Name)), RepositoryConstants.RepositoryComponent); } return(repository); } }
public async Task PerformTask() { List <WeightedEdge> weightedEdges = await FileReader.ReadWeightedEdgesList(@"Assets/" + FileName); //vertices numbers required for this task int[] taskVertices = new int[] { 7, 37, 59, 82, 99, 115, 133, 165, 188, 197 }; if (weightedEdges != null) { Benchmark.Start(TaskDescription); var shortestPaths = Compute(weightedEdges); var shortestPathsToFind = taskVertices.Select(v => shortestPaths[v]).ToArray(); Console.WriteLine("Shortest distances for task are {0}", string.Join(",", shortestPathsToFind)); Benchmark.Finish(); } }
public void ToDictionary() { var obj = new { name = "test", num = 1337 }; var actual = obj.ToDictionary(); Assert.Equal(2, actual.Count); Assert.Equal("test", actual["name"]); Assert.Equal(1337, actual["num"]); Benchmark.Start("Converting object to dictionary..", this.outputHelper); for (int i = 0; i < 10000; i++) { obj.ToDictionary(); } Benchmark.End(this.outputHelper); }
static void Main(string[] args) { if (args != null && args.Length > 0) { Setting.SERVER_HOST = args[0]; } Benchmark benchmark = new Benchmark(); benchmark.Register(typeof(Program).Assembly); benchmark.Start(); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { benchmark.OpenWeb(); } benchmark.HttpApiServer.Log(BeetleX.EventArgs.LogType.Info, $"rpc server [{Setting.SERVER_HOST}]"); Console.Read(); }
public IEnumerable <object> GetServices(Type serviceType) { using (var benchmark = Benchmark.Start()) { IReadOnlyList <object> services = Container.TryGetAll(serviceType); benchmark.Stop(); if (services.Count == 0) { Logger.Warn(Logger.Completed(benchmark.TotalTime, false, serviceType.Name), ApiConstants.IoCComponent); } else { Logger.Info(Logger.Completed(benchmark.TotalTime, true, serviceType.Name), ApiConstants.IoCComponent); } return(services); } }
private void btTest13_Click(object sender, RoutedEventArgs e) { Benchmark bm=new Benchmark(@"D:\temp\DBreezeBenchmark"); //Benchmark bm = new Benchmark(@"S:\temp\DBreezeBenchmark"); bm.Start(); }