internal static Options?ParseOptions(Arguments arguments) { var options = new Options { Benchmark = arguments.Benchmark, Runs = arguments.Runs }; if (arguments.MultiThreaded && (arguments.SingleThreaded || arguments.SingleMultiThreaded) || arguments.SingleThreaded && arguments.SingleMultiThreaded) { Console.WriteLine("Only one mode can be specified"); return(null); } if (arguments.MultiThreaded) { options.BenchmarkingMode = Options.Mode.MULTI_THREADED; } else if (arguments.SingleThreaded) { options.BenchmarkingMode = Options.Mode.SINGLE_THREADED; } else { options.BenchmarkingMode = Options.Mode.BOTH; } if (arguments.ListBenchmarks) { Console.WriteLine(string.Join(Environment.NewLine, new Runner(options, new NullLogger <Runner>()).GetListOfBenchmarksAndCategories())); return(null); } if (arguments.ListResults) { var saver = new ResultSaver(); foreach (var saveName in saver.GetListOfSaves()) { var save = saver.GetSave(saveName); if (save is null) { continue; } Console.WriteLine(); Console.WriteLine(Util.FormatResults(new Dictionary <int, List <Result> > { { 1, save.SingleThreadedResults },
private static Options?GetOptions(string[] args) { var arguments = new Arguments(); #if (RELEASE && FALSE) Parser.Default.ParseArguments <Options>(args).WithParsed(opts => { options = opts; if (opts == null) { return; } if (opts.Threads == 0) { if (opts.Multithreaded) { options.Threads = (uint)Environment.ProcessorCount; } else { options.Threads = 1; } } }); if (args.Contains("--help") || args.Contains("-h")) { return; } if (options.ClearSave) { ResultSaver.Clear(); Console.WriteLine("Successfully cleared all saved data!"); Console.ReadLine(); return; } #else arguments = new Arguments { Benchmark = "parsing" }; #endif return(OptionParser.ParseOptions(arguments)); }
private static void Main(string[] args) { var saver = new ResultSaver(); AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => CurrentDomainOnProcessExit(sender, eventArgs, saver); Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal; var options = GetOptions(args); if (options is null) { return; } Console.WriteLine("Gathering hardware information..."); var information = MachineInformationGatherer.GatherInformation(); Console.WriteLine("OS: {0}", information.OperatingSystem); Console.WriteLine("Processor: {0}", information.Cpu.Name); Console.WriteLine("Architecture: {0}", information.Cpu.Architecture); Console.WriteLine("Logical Cores: {0}", information.Cpu.LogicalCores); Console.WriteLine("Physical Cores: {0}", information.Cpu.PhysicalCores); Console.WriteLine(); Console.WriteLine("Starting Benchmark..."); Console.WriteLine(); var runner = new Runner(options, new NullLogger <Runner>()); Console.WriteLine("Running the following benchmarks in approx. {1}: {0}", string.Join(", ", runner.GetBenchmarksToRun().Select(benchmark => benchmark.GetName())), Helper.FormatTime(runner.GetTotalTime())); Console.WriteLine(); Console.WriteLine(); using var ct = new CancellationTokenSource(); var t = new Thread(() => DisplayProgressbar(ref runner, ref options, ct.Token)); t.Start(); runner.RunBenchmarks(); ct.Cancel(); t.Join(); saver.CreateOrUpdateSaveForCurrentRun(information, runner.Results); var save = saver.GetSave("current"); if (save is null) { return; } Console.WriteLine(); Console.WriteLine( Util.FormatResults(new Dictionary <int, List <Result> > { { 1, save.SingleThreadedResults }, { Environment.ProcessorCount, save.MultiThreadedResults } })); Console.WriteLine(); }
private static void CurrentDomainOnProcessExit(object?sender, EventArgs e, ResultSaver saver) { saver.WriteSaves(); }
private void RunGenericBenchmark() { var categories = new Dictionary <string, List <Result> >(); while (benchmarksToRun.Count > 0) { var currentBenchmark = benchmarksToRun[0]; lock (CurrentRunningBenchmark) { CurrentRunningBenchmark = currentBenchmark.GetName(); CurrentBenchmarkFinished = 0; } foreach (var category in currentBenchmark.GetCategories()) { if (!categories.ContainsKey(category)) { categories.Add(category, new List <Result>()); } } // Execute currentBenchmark.Initialize(); CurrentBenchmarkFinished = 0; CurrentRunningBenchmark = currentBenchmark.GetName(); var timing = ExecuteBenchmark(); currentBenchmark.Shutdown(); var result = new Result( currentBenchmark.GetName(), timing, currentBenchmark.GetRatingMethod().Invoke(timing), currentBenchmark.GetComparison(), currentBenchmark.GetRatingMethod().Invoke(currentBenchmark.GetComparison()), currentBenchmark.GetDataThroughput(timing) / BenchmarkRater.ScaleVolume(options.Threads) ); Results.Add(result); foreach (var category in currentBenchmark.GetCategories()) { categories[category].Add(result); } benchmarksToRun.RemoveAt(0); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ProcessCategories(categories); // Add to save foreach (var runnerResult in Results) { ResultSaver.SaveResult(options.Threads, runnerResult); } // Check for newly completed categories ResultCategoryAggregator.ProcessCategories(options, categories); }
internal static bool ParseOptions(Options options) { if (options.ListBenchmarks) { Console.WriteLine(string.Join(Environment.NewLine, BenchmarkRunner.GetAvailableBenchmarks())); return(false); } if (options.ListResults) { ResultSaver.Init(options); Console.WriteLine(); Console.WriteLine(Util.FormatResults(ResultSaver.GetResults())); return(false); } if (options.Upload) { if (!ResultSaver.Init(options)) { Console.WriteLine( "A restart or hardware change has been detected. Please redo the benchmark and upload it without restarting."); return(false); } var result = ResultSaver.IsAllowedToUpload(options); if (result == ErrorCode.NOT_WINDOWS) { Console.WriteLine("You can only upload your results on a Windows machine."); return(false); } if (result == ErrorCode.NO_CATEGORY_ALL) { Console.WriteLine("You can only upload your results after having completed all benchmarks."); return(false); } Console.WriteLine(); Console.WriteLine("Uploading results..."); var response = ResultSaver.UploadResults().Result; if (response != null) { Console.WriteLine("Done!"); Console.WriteLine("You can view your raw save here: {0}", response.RawPath); Console.WriteLine("You can view your parsed save here: {0}", response.WebsitePath); Console.WriteLine( "Click 'a' to open raw, 'b' to open parsed or any other key to close the program!"); while (true) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.A) { Helper.OpenBrowser(response.RawPath); } else if (key.Key == ConsoleKey.B) { Helper.OpenBrowser(response.WebsitePath); } else { return(false); } } } Console.WriteLine("Failed uploading results!"); return(false); } if (options.Benchmark == null || string.IsNullOrWhiteSpace(options.Benchmark)) { Console.WriteLine("Please specify a benchmark!"); return(false); } if (!BenchmarkRunner.GetAvailableBenchmarks() .Any(a => a.ToLowerInvariant().Equals(options.Benchmark.ToLowerInvariant()))) { Console.WriteLine("Benchmark name not recognized!"); return(false); } return(true); }
private async void ButtonStart_Click(object sender, EventArgs e) { // Отмена задачи - исключительная ситуация. Наверное, нормально. // Проверка на 0 if (BoxNumber.Text == string.Empty || BoxNumber.Text == @"0") { MessageBox.Show(@"Введите N > 0, чтобы начать вычисления"); return; } var N = int.Parse(BoxNumber.Text); #region StartActions BoxResult.Clear(); PanelResult.Visible = true; ButtonCancel.Visible = true; ButtonStart.Enabled = false; ButtonCancel.Enabled = true; #endregion #region Job var dateTimeStart = DateTime.Now; var cts = new CancellationTokenSource(); ButtonCancel.Click += (sender1, e1) => cts.Cancel(); // анонимный метод, не лямбда. Лямбда - другой объект, который, тем не менее, может конвертироваться. Closing += (o, args) => cts.Cancel(); IProgress <int> progress = new Progress <int>(percentage => progressBar1.Value = percentage); // Handler - это Invoke, короче. Если быть точным, то SynchronizationContext.Post. Который посылает асинхронное сообщение в нужный синхр. контекст. Invoke, короче. var result = new long[N]; //var sbResultForTextBox = new StringBuilder(N * 5); var stringResult = string.Empty; var task = new Task(WorkWithResult, cts.Token); task.Start(); label1.Text = @"Генерация..."; try { await task.ConfigureAwait(true); } catch (OperationCanceledException) { // не знаю, что тут еще делать. Можно бы установить какой-то bool в true, но это и так есть в task.IsCanceled. } label1.Text = @"Вывод результата..."; ButtonCancel.Enabled = false; if (!task.IsCanceled) { progress.Report(0); var numberInsertions = stringResult.Length / 10_000; var lastInsertion = stringResult.Length % 10_1000; var progressValue = 0.0; var progressUnit = 100d / (numberInsertions + (lastInsertion > 0 ? 1 : 0)); for (var i = 0; i < numberInsertions; i++) { await Task.Delay(1).ConfigureAwait(true); BoxResult.AppendText(stringResult.Substring(i * 10_000, 10_000)); progress.Report((int)(progressValue += progressUnit)); } if (lastInsertion != 0) { await Task.Delay(1).ConfigureAwait(true); BoxResult.AppendText(stringResult.Substring(stringResult.Length - lastInsertion, lastInsertion)); progress.Report((int)(progressValue + progressUnit)); } } ActionsLog.Add(new ActionsLogRecord(Users.CurrentUserName, N, task.IsCanceled, dateTimeStart)); var typeOfFile = CBoxTypeOfFile.SelectedIndex; string directoryForResult; if (typeOfFile > 0) { directoryForResult = BoxDirectoryForResult.Text; label1.Text = @"Сохранение..."; // ReSharper disable once MethodSupportsCancellation ButtonCancel.Enabled = false; await SaveToFile().ConfigureAwait(true); // отмены в этом методе нет. ButtonCancel.Enabled = true; } #endregion #region FinalActions progress.Report(0); PanelResultSettings.Enabled = true; ButtonChangeUser.Enabled = true; ButtonCancel.Visible = false; ButtonStart.Enabled = true; label1.Text = task.IsCanceled ? "Отменено" : "Готово"; #endregion void WorkWithResult() { { var sbResult = new StringBuilder(N * 5); var progressValue = 0.0; var progressStep = 100d / N / 2; result[0] = PrimeNumbers.Next_prime(0); progress.Report((int)(progressValue += progressStep * 2)); for (var i = 0; i < result.Length - 1; i++) { result[i + 1] = PrimeNumbers.Next_prime(result[i]); cts.Token .ThrowIfCancellationRequested(); progressValue += progressStep * 2; if (i % 1000 == 0) { progress.Report((int)progressValue); } } // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < result.Length; i++) { var number = result[i]; sbResult.AppendLine(number.ToString()); cts.Token .ThrowIfCancellationRequested(); } stringResult = sbResult.ToString(); } } Task SaveToFile() { var localTask = new Task(() => { var resultSaver = new ResultSaver <long>(result, SettingsForResult.ItemResultSeparator); try { resultSaver.SetDirectoryForResult(directoryForResult); } catch (Exception) { MessageBox.Show($@"Не удается создать указанный путь ""{ directoryForResult }"" для сохранения результата. Возможно, вы назначили сохранение на флешку, а затем вытащили ее."); return; } var actionsSaveResult = new Dictionary <int, Action <IProgress <int>, string, bool> > { [1] = resultSaver.SaveTextResultTo, [2] = resultSaver.SavePdfResultTo }; actionsSaveResult[typeOfFile] .Invoke(progress, string.Empty, false); //Invoke - потому что делегат. if (typeOfFile > 0) { MessageBox.Show($@"Результат сохранен в указанную папку ""{directoryForResult}""", @"Уведомление"); } }); localTask.Start(); return(localTask); } }
private static void Main(string[] args) { var options = new Options(); #if RELEASE Parser.Default.ParseArguments <Options>(args).WithParsed(opts => { options = opts; if (opts == null) { return; } if (opts.Threads == 0) { if (opts.Multithreaded) { options.Threads = (uint)Environment.ProcessorCount; } else { options.Threads = 1; } } }); if (args.Contains("--help") || args.Contains("-h")) { return; } if (options.ClearSave) { ResultSaver.Clear(); Console.WriteLine("Successfully cleared all saved data!"); Console.ReadLine(); return; } #else options = new Options { Benchmark = "avx2int", Threads = 1, Runs = 1 }; #endif if (!OptionParser.ParseOptions(options)) { Console.ReadLine(); return; } Console.WriteLine("Gathering hardware information..."); var information = MachineInformationGatherer.GatherInformation(); Console.WriteLine("OS: {0}", information.OperatingSystem); Console.WriteLine("Processor: {0}", information.Cpu.Name); Console.WriteLine("Architecture: {0}", information.Cpu.Architecture); Console.WriteLine("Logical Cores: {0}", information.Cpu.LogicalCores); Console.WriteLine("Physical Cores: {0}", information.Cpu.PhysicalCores); Console.WriteLine(); if (options.Stress) { var cancellationTokenSource = new CancellationTokenSource(); var consoleTask = Task.Run(() => { Thread.CurrentThread.Priority = ThreadPriority.Highest; Console.WriteLine("Press any key to stop the stress test."); Console.ReadKey(true); cancellationTokenSource.Cancel(); }); var stressTester = new StressTestRunner(options); stressTester.Prepare(); var completed = stressTester.RunStressTest(cancellationTokenSource.Token); Task.WaitAll(consoleTask); Console.WriteLine("You've completed {0} benchmark iteration{1}; ~{2} per thread.", completed, completed == 1 ? "" : "s", Math.Round(completed / (double)options.Threads, 2)); return; } Console.WriteLine("Starting Benchmark..."); Console.WriteLine(); ResultSaver.Init(options); var runner = new BenchmarkRunner(options, information); runner.Prepare(); var poptions = new ProgressBarOptions { ForegroundColor = ConsoleColor.Yellow, BackgroundColor = ConsoleColor.DarkYellow, ProgressCharacter = '─', ProgressBarOnBottom = true, CollapseWhenFinished = false }; using (var pbar = new ProgressBar((int)BenchmarkRunner.TotalOverall, $"Running Benchmark {options.Benchmark} on {options.Threads} threads {options.Runs} times", poptions)) { using var ct = new CancellationTokenSource(); var t = Task.Run(() => { Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; while (!ct.IsCancellationRequested) { lock (BenchmarkRunner.CurrentRunningBenchmark) { pbar.Tick(BenchmarkRunner.FinishedOverall, $"Overall. Currently running {BenchmarkRunner.CurrentRunningBenchmark} on {options.Threads} threads {options.Runs} times"); } Thread.Sleep(200); } }, ct.Token); try { runner.RunBenchmark(); } catch (ArgumentException e) { Console.WriteLine(e.Message); return; } pbar.Tick((int)BenchmarkRunner.TotalOverall); ct.Cancel(); pbar.Tick((int)BenchmarkRunner.TotalOverall); t.GetAwaiter().GetResult(); } Console.WriteLine(); Console.WriteLine( Util.FormatResults(new Dictionary <uint, List <Result> > { { options.Threads, runner.Results } })); Console.ReadLine(); }