From 2ba30330ec5ec8a9abe284c927277a6fe0fc5a0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Nag=C3=B3rski?= Date: Tue, 1 Oct 2019 15:12:48 +0200 Subject: [PATCH] Task remove trailing whitespace (#1259) * Remove all trailing whitespaces --- .../IntroCategories.cs | 4 +- .../IntroDeferredExecution.cs | 8 +- .../IntroDisassemblyAllJits.cs | 2 +- .../IntroDisassemblyDry.cs | 2 +- .../BenchmarkDotNet.Samples/IntroEncoding.cs | 6 +- .../BenchmarkDotNet.Samples/IntroEnvVars.cs | 2 +- .../IntroExportJson.cs | 8 +- .../BenchmarkDotNet.Samples/IntroFilters.cs | 4 +- .../IntroFluentConfigBuilder.cs | 2 +- .../IntroHardwareCounters.cs | 2 +- .../IntroJobBaseline.cs | 2 +- samples/BenchmarkDotNet.Samples/IntroJoin.cs | 6 +- .../IntroMultimodal.cs | 2 +- samples/BenchmarkDotNet.Samples/IntroNuGet.cs | 2 +- .../IntroOrderManual.cs | 2 +- .../IntroSetupCleanupGlobal.cs | 4 +- .../IntroSetupCleanupTarget.cs | 12 +-- .../Attributes/GlobalCleanupAttribute.cs | 2 +- .../Attributes/ParamsAttribute.cs | 2 +- .../ConcurrencyVisualizerProfiler.cs | 10 +-- .../EtwDiagnoser.cs | 4 +- .../HardwareCounters.cs | 4 +- .../InliningDiagnoser.cs | 8 +- .../PmcDiagnoser.cs | 2 +- .../Tracing/IterationEvent.cs | 4 +- src/BenchmarkDotNet/Analysers/AnalyserBase.cs | 6 +- src/BenchmarkDotNet/Analysers/Conclusion.cs | 16 ++-- .../MultimodalDistributionAnalyzer.cs | 2 +- .../Analysers/OutliersAnalyser.cs | 2 +- .../Analysers/ZeroMeasurementAnalyser.cs | 12 +-- .../Columns/ColumnConfigBaseAttribute.cs | 2 +- .../WelchTTestPValueColumnAttribute.cs | 2 +- .../Attributes/EncodingAttribute.cs | 2 +- .../Filters/AllCategoriesFilterAttribute.cs | 2 +- .../Filters/AnyCategoriesFilterAttribute.cs | 2 +- .../Filters/FilterConfigBaseAttribute.cs | 2 +- .../Attributes/GroupBenchmarksByAttribute.cs | 2 +- .../Attributes/Jobs/MonoJobAttribute.cs | 2 +- .../Mutators/InnerIterationCountAttribute.cs | 2 +- .../Mutators/JobMutatorConfigBaseAttribute.cs | 4 +- .../Mutators/MaxWarmupCountAttribute.cs | 6 +- .../Mutators/MinWarmupCountAttribute.cs | 6 +- .../Mutators/WarmupCountAttribute.cs | 2 +- .../Attributes/OrdererAttribute.cs | 2 +- .../Attributes/StopOnFirstErrorAttribute.cs | 2 +- .../Characteristics/Characteristic.cs | 16 ++-- .../Characteristics/CharacteristicObject.cs | 6 +- .../Characteristics/CharacteristicObject`1.cs | 4 +- .../CharacteristicPresenter.cs | 14 ++-- .../CharacteristicSetPresenter.cs | 2 +- src/BenchmarkDotNet/Code/ArrayParam.cs | 2 +- src/BenchmarkDotNet/Code/CodeGenerator.cs | 6 +- .../Code/DeclarationsProvider.cs | 4 +- .../Columns/BaselineScaledColumn.cs | 4 +- .../Columns/CategoriesColumn.cs | 2 +- .../Columns/DefaultColumnProvider.cs | 4 +- .../Columns/JobCharacteristicColumn.cs | 2 +- src/BenchmarkDotNet/Columns/MetricColumn.cs | 4 +- src/BenchmarkDotNet/Columns/RankColumn.cs | 2 +- .../Columns/StatisticColumn.cs | 8 +- src/BenchmarkDotNet/Configs/ConfigOptions.cs | 2 +- src/BenchmarkDotNet/Configs/DebugConfig.cs | 2 +- src/BenchmarkDotNet/Configs/DefaultConfig.cs | 2 +- src/BenchmarkDotNet/Configs/IConfig.cs | 4 +- .../Configs/ImmutableConfig.cs | 12 +-- .../ConsoleArguments/CommandLineOptions.cs | 36 ++++----- .../ConsoleArguments/ConfigParser.cs | 16 ++-- .../ConsoleArguments/CorrectionsSuggester.cs | 8 +- .../ListBenchmarks/BenchmarkCasesPrinter.cs | 2 +- .../FlatBenchmarkCasesPrinter.cs | 2 +- .../Diagnosers/CompositeDiagnoser.cs | 6 +- .../Diagnosers/CopiedDataContracts.cs | 2 +- .../Diagnosers/DisassemblyPrettifier.cs | 4 +- .../Diagnosers/MemoryDiagnoser.cs | 8 +- .../Diagnosers/MonoDisassembler.cs | 10 +-- .../Diagnosers/PmcMetricDescriptor.cs | 2 +- .../Diagnosers/UnresolvedDiagnoser.cs | 4 +- src/BenchmarkDotNet/Engines/ConsoleHost.cs | 2 +- src/BenchmarkDotNet/Engines/Consumer.cs | 4 +- .../Engines/ConsumerExtensions.cs | 6 +- src/BenchmarkDotNet/Engines/Engine.cs | 16 ++-- .../Engines/EngineEventSource.cs | 40 +++++----- src/BenchmarkDotNet/Engines/EngineFactory.cs | 28 +++---- .../Engines/EngineGeneralStage.cs | 4 +- .../Engines/EngineParameters.cs | 12 +-- src/BenchmarkDotNet/Engines/EngineResolver.cs | 2 +- src/BenchmarkDotNet/Engines/EngineStage.cs | 2 +- src/BenchmarkDotNet/Engines/GcStats.cs | 10 +-- src/BenchmarkDotNet/Engines/HostExtensions.cs | 2 +- src/BenchmarkDotNet/Engines/HostSignal.cs | 4 +- src/BenchmarkDotNet/Engines/IterationMode.cs | 4 +- src/BenchmarkDotNet/Engines/IterationStage.cs | 10 +-- src/BenchmarkDotNet/Engines/RunResults.cs | 4 +- .../StoppingCriteria/IStoppingCriteria.cs | 4 +- src/BenchmarkDotNet/Engines/ThreadingStats.cs | 2 +- .../Environments/EnvironmentResolver.cs | 2 +- .../Environments/HostEnvironmentInfo.cs | 4 +- src/BenchmarkDotNet/Environments/Jit.cs | 2 +- .../Environments/OsBrandStringHelper.cs | 2 +- src/BenchmarkDotNet/Environments/Platform.cs | 4 +- .../ProcessorBrandStringHelper.cs | 6 +- .../Environments/Runtimes/ClrRuntime.cs | 2 +- .../Environments/Runtimes/CoreRuntime.cs | 4 +- .../Environments/Runtimes/MonoRuntime.cs | 4 +- .../Environments/Runtimes/Runtime.cs | 2 +- .../Exporters/BenchmarkReportExporter.cs | 2 +- .../Exporters/CombinedDisassemblyExporter.cs | 14 ++-- .../Exporters/CompositeExporter.cs | 4 +- .../Exporters/Csv/CsvMeasurementsExporter.cs | 2 +- .../Exporters/FullNameProvider.cs | 12 +-- .../Exporters/Json/JsonExporterBase.cs | 2 +- .../PrettyHtmlDisassemblyExporter.cs | 4 +- .../Exporters/RawDisassemblyExporter.cs | 4 +- .../Extensions/CommonExtensions.cs | 4 +- .../Extensions/EncodingExtensions.cs | 2 +- .../Extensions/ProcessExtensions.cs | 4 +- .../Extensions/ReflectionExtensions.cs | 26 +++---- .../Extensions/StringAndTextExtensions.cs | 6 +- src/BenchmarkDotNet/Filters/GlobFilter.cs | 2 +- .../Helpers/CodeAnnotations.cs | 24 +++--- .../Helpers/DirtyAssemblyResolveHelper.cs | 6 +- .../Helpers/FolderNameHelper.cs | 4 +- .../Helpers/FrameworkVersionHelper.cs | 2 +- .../Helpers/GenericBenchmarksBuilder.cs | 8 +- .../Helpers/MultiEncodingString.cs | 26 +++---- .../Helpers/SourceCodeHelper.cs | 8 +- .../Helpers/UserInteractionHelper.cs | 2 +- src/BenchmarkDotNet/Horology/Frequency.cs | 6 +- src/BenchmarkDotNet/Horology/FrequencyUnit.cs | 2 +- .../Horology/TimeSpanExtensions.cs | 2 +- src/BenchmarkDotNet/Horology/TimeUnit.cs | 2 +- src/BenchmarkDotNet/Jobs/EnvironmentMode.cs | 2 +- src/BenchmarkDotNet/Jobs/GcMode.cs | 4 +- src/BenchmarkDotNet/Jobs/GcModeExtensions.cs | 4 +- .../Jobs/InfrastructureMode.cs | 2 +- src/BenchmarkDotNet/Jobs/JobExtensions.cs | 10 +-- src/BenchmarkDotNet/Jobs/JobIdGenerator.cs | 2 +- src/BenchmarkDotNet/Jobs/MetaMode.cs | 4 +- src/BenchmarkDotNet/Jobs/NugetReference.cs | 2 +- src/BenchmarkDotNet/Jobs/RunMode.cs | 6 +- .../Loggers/LoggerWithPrefix.cs | 2 +- ...hronousProcessOutputLoggerWithDiagnoser.cs | 2 +- .../Mathematics/BinomialCoefficientHelper.cs | 6 +- .../Histograms/AdaptiveHistogramBuilder.cs | 2 +- .../Mathematics/Histograms/BinSizeRule.cs | 10 +-- .../Histograms/IHistogramBuilder.cs | 2 +- .../Histograms/SimpleHistogramBuilder.cs | 6 +- src/BenchmarkDotNet/Mathematics/MathHelper.cs | 14 ++-- .../Mathematics/MeasurementsStatistics.cs | 2 +- .../Mathematics/NumeralSystem.cs | 4 +- .../Mathematics/OutlierMode.cs | 14 ++-- .../Mathematics/PercentileValues.cs | 2 +- .../StatisticalTesting/OneSidedTestResult.cs | 8 +- .../StatisticalTestHelper.cs | 4 +- .../StatisticalTesting/StudentTest.cs | 12 +-- .../StatisticalTesting/Threshold.cs | 2 +- .../StatisticalTesting/ThresholdUnit.cs | 2 +- .../StatisticalTesting/WelchResult.cs | 2 +- .../StatisticalTesting/WelchTest.cs | 2 +- src/BenchmarkDotNet/Mathematics/Statistics.cs | 6 +- src/BenchmarkDotNet/Order/DefaultOrderer.cs | 10 +-- src/BenchmarkDotNet/Order/IOrderer.cs | 2 +- .../Parameters/ParameterInstance.cs | 8 +- .../Parameters/SmartParamBuilder.cs | 12 +-- .../Portability/Cpu/CpuInfo.cs | 2 +- .../Portability/Cpu/CpuInfoFormatter.cs | 4 +- .../Portability/Cpu/ProcCpuInfoParser.cs | 8 +- .../Portability/Cpu/ProcCpuInfoProvider.cs | 4 +- .../Portability/Cpu/SysctlCpuInfoParser.cs | 2 +- .../Portability/Cpu/SysctlCpuInfoProvider.cs | 2 +- .../Portability/Cpu/WmicCpuInfoParser.cs | 6 +- .../Portability/RuntimeInformation.cs | 10 +-- .../Reports/BenchmarkReport.cs | 2 +- .../Reports/DisplayPrecisionManager.cs | 2 +- src/BenchmarkDotNet/Reports/Measurement.cs | 26 +++---- src/BenchmarkDotNet/Reports/Metric.cs | 8 +- src/BenchmarkDotNet/Reports/Summary.cs | 20 ++--- .../Reports/SummaryTableExtensions.cs | 2 +- .../Running/BenchmarkConverter.cs | 8 +- src/BenchmarkDotNet/Running/BenchmarkId.cs | 2 +- .../Running/BenchmarkRunnerClean.cs | 32 ++++---- .../Running/BenchmarkRunnerDirty.cs | 2 +- .../Running/BenchmarkSwitcher.cs | 2 +- src/BenchmarkDotNet/Running/Descriptor.cs | 2 +- .../Running/IUserInteraction.cs | 4 +- src/BenchmarkDotNet/Running/TypeFilter.cs | 4 +- .../Toolchains/CoreRt/CoreRtToolchain.cs | 10 +-- .../CoreRt/CoreRtToolchainBuilder.cs | 2 +- .../Toolchains/CoreRt/Generator.cs | 8 +- .../Toolchains/CoreRun/CoreRunGenerator.cs | 14 ++-- .../Toolchains/CoreRun/CoreRunPublisher.cs | 12 +-- .../Toolchains/CoreRun/CoreRunToolchain.cs | 16 ++-- .../Toolchains/CsProj/CsProjCoreToolchain.cs | 6 +- .../Toolchains/CsProj/CsProjGenerator.cs | 2 +- .../Toolchains/DotNetCli/DotNetCliCommand.cs | 22 +++--- .../DotNetCli/DotNetCliCommandExecutor.cs | 2 +- .../DotNetCli/DotNetCliCommandResult.cs | 2 +- .../Toolchains/DotNetCli/DotNetCliExecutor.cs | 12 +-- .../DotNetCli/DotNetCliGenerator.cs | 4 +- .../DotNetCli/DotNetCliPublisher.cs | 10 +-- .../DotNetCli/MsBuildErrorMapper.cs | 2 +- .../DotNetCli/NetCoreAppSettings.cs | 10 +-- .../Toolchains/GeneratorBase.cs | 2 +- .../Emitters/NonConsumableConsumeEmitter.cs | 2 +- .../Emitters/RunnableEmitter.cs | 14 ++-- .../Toolchains/Results/BuildResult.cs | 2 +- .../Toolchains/Results/GenerateResult.cs | 4 +- .../Toolchains/Roslyn/Generator.cs | 6 +- .../Toolchains/Roslyn/RoslynToolchain.cs | 2 +- .../Toolchains/Roslyn/RoslynWorkarounds.cs | 2 +- src/BenchmarkDotNet/Toolchains/Toolchain.cs | 2 +- .../Toolchains/ToolchainExtensions.cs | 2 +- .../Validators/BaselineValidator.cs | 10 +-- .../Validators/CompilationValidator.cs | 2 +- .../Validators/CompositeValidator.cs | 4 +- .../Validators/DeferredExecutionValidator.cs | 6 +- .../Validators/GenericBenchmarksValidator.cs | 4 +- .../Validators/ParamsAllValuesValidator.cs | 4 +- .../Validators/RunModeValidator.cs | 8 +- .../Validators/ValidationError.cs | 2 +- .../Validators/ValidationErrorReporter.cs | 2 +- .../OptimizationsDisabledInCsproj.cs | 2 +- .../LocalCoreRtToolchainTests.cs | 2 +- .../AllSetupAndCleanupTest.cs | 8 +- .../BenchmarkSwitcherTest.cs | 50 ++++++------ .../BenchmarkTestExecutor.cs | 6 +- .../BuildTimeoutTests.cs | 4 +- .../CoreRtTests.cs | 2 +- .../CustomEngineTests.cs | 6 +- .../Diagnosers/ProcessMetricsTests.cs | 24 +++--- .../DisassemblyDiagnoserTests.cs | 2 +- .../ExporterIOTests.cs | 2 +- .../GlobalCleanupAttributeTargetTest.cs | 2 +- .../GlobalSetupAttributeTargetTest.cs | 6 +- .../JitRuntimeValidationTest.cs | 2 +- .../MemoryDiagnoserTests.cs | 2 +- .../NugetReferenceTests.cs | 2 +- .../ParamsAttributeStaticTest.cs | 4 +- .../ParamsTests.cs | 10 +-- .../ProcessPropertiesTests.cs | 4 +- .../ReferencesTests.cs | 4 +- .../SetupAndCleanupTests.cs | 14 ++-- .../ValuesReturnedByBenchmarkTest.cs | 4 +- .../Analysers/ZeroMeasurementHelperTests.cs | 78 +++++++++---------- .../Builders/HostEnvironmentInfoBuilder.cs | 2 +- .../Columns/StatisticalTestColumnTests.cs | 10 +-- .../ConfigParserTests.cs | 52 ++++++------- .../Configs/ConfigOptionsTests.cs | 2 +- .../Configs/EnvironmentVariableTests.cs | 2 +- .../BenchmarkDotNet.Tests/Configs/JobTests.cs | 18 ++--- .../Engine/EngineResultStageTests.cs | 2 +- .../Engine/EngineWarmupStageTests.cs | 8 +- .../StoppingCriteriaTestsBase.cs | 4 +- .../Environments/ProcessorBrandStringTests.cs | 12 +-- .../MarkdownExporterApprovalTests.cs | 16 ++-- .../Exporters/XmlSerializerTests.cs | 4 +- .../FullNameProviderTests.cs | 54 ++++++------- .../GenericBuilderTests.cs | 40 +++++----- .../LevenshteinDistanceCalculatorTests.cs | 12 +-- .../Loggers/LoggerWithPrefixTests.cs | 20 ++--- .../Histograms/AdaptiveHistogramTests.cs | 2 +- .../Histograms/HistogramTestHelper.cs | 4 +- .../Mathematics/Histograms/HistogramTests.cs | 2 +- .../Mathematics/Histograms/MultimodalTests.cs | 2 +- .../StatisticalTesting/MannWhitneyTests.cs | 56 ++++++------- .../StatisticalTesting/StudentTests.cs | 4 +- .../BenchmarkDotNet.Tests/Mocks/MockEngine.cs | 2 +- .../Mocks/MockFactory.cs | 4 +- .../MonoDisassemblyOutputParserTests.cs | 4 +- .../MultiEncodingStringTests.cs | 10 +-- .../ParameterInstanceTests.cs | 4 +- .../Portability/Cpu/ProcCpuInfoParserTests.cs | 2 +- .../Portability/Cpu/TestHelper.cs | 2 +- .../BenchmarkDotNet.Tests/ReflectionTests.cs | 2 +- .../Reports/DefaultColumnProvidersTests.cs | 4 +- .../Reports/DisplayPrecisionManagerTests.cs | 2 +- .../Reports/SummaryTableTests.cs | 2 +- .../Running/BenchmarkConverterTests.cs | 38 ++++----- .../JobRuntimePropertiesComparerTests.cs | 2 +- .../SourceCodeHelperTests.cs | 2 +- .../SummaryStyleTests.cs | 2 +- .../BenchmarkDotNet.Tests/TypeFilterTests.cs | 16 ++-- .../Validators/CompilationValidatorTests.cs | 18 ++--- .../DeferredExecutionValidatorTests.cs | 8 +- .../XUnit/FactDotNetCore21OnlyAttribute.cs | 4 +- .../XUnit/FactWindowsOnlyAttribute.cs | 2 +- 286 files changed, 996 insertions(+), 996 deletions(-) diff --git a/samples/BenchmarkDotNet.Samples/IntroCategories.cs b/samples/BenchmarkDotNet.Samples/IntroCategories.cs index 9e9939bfbe..3319d8614c 100644 --- a/samples/BenchmarkDotNet.Samples/IntroCategories.cs +++ b/samples/BenchmarkDotNet.Samples/IntroCategories.cs @@ -12,7 +12,7 @@ public class IntroCategories [Benchmark] [BenchmarkCategory("A", "1")] public void A1() => Thread.Sleep(10); // Will be benchmarked - + [Benchmark] [BenchmarkCategory("A", "2")] public void A2() => Thread.Sleep(10); // Will be benchmarked @@ -20,7 +20,7 @@ public class IntroCategories [Benchmark] [BenchmarkCategory("B", "1")] public void B1() => Thread.Sleep(10); // Will be benchmarked - + [Benchmark] [BenchmarkCategory("B", "2")] public void B2() => Thread.Sleep(10); diff --git a/samples/BenchmarkDotNet.Samples/IntroDeferredExecution.cs b/samples/BenchmarkDotNet.Samples/IntroDeferredExecution.cs index 3b71c0cdfe..a6ec25e31d 100644 --- a/samples/BenchmarkDotNet.Samples/IntroDeferredExecution.cs +++ b/samples/BenchmarkDotNet.Samples/IntroDeferredExecution.cs @@ -7,10 +7,10 @@ namespace BenchmarkDotNet.Samples { public class IntroDeferredExecution { - private readonly int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - + private readonly int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + private readonly Consumer consumer = new Consumer(); - + /// /// this benchmark returns a deferred LINQ query which is NOT executed /// so the benchmark measures the cost of creating the query, not the actual execution @@ -20,7 +20,7 @@ public class IntroDeferredExecution /// deferred LINQ query [Benchmark] public IEnumerable Wrong() => from number in numbers orderby number descending select number; - + /// /// this benchmark uses .Consume extension method which executes given deferred query and consumes its result /// so the benchmark measures the cost of creating the query and executing it diff --git a/samples/BenchmarkDotNet.Samples/IntroDisassemblyAllJits.cs b/samples/BenchmarkDotNet.Samples/IntroDisassemblyAllJits.cs index ca0af4d2b0..b097513e7a 100644 --- a/samples/BenchmarkDotNet.Samples/IntroDisassemblyAllJits.cs +++ b/samples/BenchmarkDotNet.Samples/IntroDisassemblyAllJits.cs @@ -31,7 +31,7 @@ public MultipleJits() Add(DisassemblyDiagnoser.Create(new DisassemblyDiagnoserConfig(printAsm: true, printPrologAndEpilog: true, recursiveDepth: 3, printDiff: true))); } } - + private Increment increment = new Increment(); [Benchmark] diff --git a/samples/BenchmarkDotNet.Samples/IntroDisassemblyDry.cs b/samples/BenchmarkDotNet.Samples/IntroDisassemblyDry.cs index caee7ea733..f2cbc05a2d 100644 --- a/samples/BenchmarkDotNet.Samples/IntroDisassemblyDry.cs +++ b/samples/BenchmarkDotNet.Samples/IntroDisassemblyDry.cs @@ -23,7 +23,7 @@ public JustDisassembly() [Benchmark] public void Foo() { - + } } } \ No newline at end of file diff --git a/samples/BenchmarkDotNet.Samples/IntroEncoding.cs b/samples/BenchmarkDotNet.Samples/IntroEncoding.cs index e0ae227a11..b6c552fc1d 100644 --- a/samples/BenchmarkDotNet.Samples/IntroEncoding.cs +++ b/samples/BenchmarkDotNet.Samples/IntroEncoding.cs @@ -7,7 +7,7 @@ namespace BenchmarkDotNet.Samples { // *** Attribute Style *** - + [EncodingAttribute.Unicode] public class IntroEncoding { @@ -20,7 +20,7 @@ public long Foo() return waitUntil; } } - + // *** Object Style *** [Config(typeof(Config))] @@ -40,7 +40,7 @@ public long Foo() return waitUntil; } } - + // *** Fluent Config *** public class IntroEncodingFluentConfig diff --git a/samples/BenchmarkDotNet.Samples/IntroEnvVars.cs b/samples/BenchmarkDotNet.Samples/IntroEnvVars.cs index 52b26c5ba7..1098687bbb 100644 --- a/samples/BenchmarkDotNet.Samples/IntroEnvVars.cs +++ b/samples/BenchmarkDotNet.Samples/IntroEnvVars.cs @@ -11,7 +11,7 @@ public class IntroEnvVars private class ConfigWithCustomEnvVars : ManualConfig { private const string JitNoInline = "COMPlus_JitNoInline"; - + public ConfigWithCustomEnvVars() { Add(Job.Default.With(CoreRuntime.Core21).WithId("Inlining enabled")); diff --git a/samples/BenchmarkDotNet.Samples/IntroExportJson.cs b/samples/BenchmarkDotNet.Samples/IntroExportJson.cs index 72170464ea..62f95a605c 100644 --- a/samples/BenchmarkDotNet.Samples/IntroExportJson.cs +++ b/samples/BenchmarkDotNet.Samples/IntroExportJson.cs @@ -6,7 +6,7 @@ namespace BenchmarkDotNet.Samples { // *** Attribute style *** - + [DryJob] [JsonExporterAttribute.Brief] [JsonExporterAttribute.Full] @@ -18,9 +18,9 @@ public class IntroExportJson [Benchmark] public void Sleep10() => Thread.Sleep(10); [Benchmark] public void Sleep20() => Thread.Sleep(20); } - + // *** Object style *** - + [Config(typeof(Config))] public class IntroJsonExportObjectStyle { @@ -35,7 +35,7 @@ public Config() Add(JsonExporter.Custom("-custom", indentJson: true, excludeMeasurements: true)); } } - + [Benchmark] public void Sleep10() => Thread.Sleep(10); [Benchmark] public void Sleep20() => Thread.Sleep(20); } diff --git a/samples/BenchmarkDotNet.Samples/IntroFilters.cs b/samples/BenchmarkDotNet.Samples/IntroFilters.cs index 70cdcc62fe..80c693d75f 100644 --- a/samples/BenchmarkDotNet.Samples/IntroFilters.cs +++ b/samples/BenchmarkDotNet.Samples/IntroFilters.cs @@ -20,12 +20,12 @@ public Config() new NameFilter(name => name.Contains("A")), new NameFilter(name => name.Contains("1")) )); - + // benchmark with names with length < 3 Add(new NameFilter(name => name.Length < 3)); } } - + [Benchmark] public void A1() => Thread.Sleep(10); // Will be benchmarked [Benchmark] public void A2() => Thread.Sleep(10); // Will be benchmarked [Benchmark] public void A3() => Thread.Sleep(10); // Will be benchmarked diff --git a/samples/BenchmarkDotNet.Samples/IntroFluentConfigBuilder.cs b/samples/BenchmarkDotNet.Samples/IntroFluentConfigBuilder.cs index 2908cd521c..b815c0e2b6 100644 --- a/samples/BenchmarkDotNet.Samples/IntroFluentConfigBuilder.cs +++ b/samples/BenchmarkDotNet.Samples/IntroFluentConfigBuilder.cs @@ -29,7 +29,7 @@ public Algo_Md5VsSha256() [Benchmark] public byte[] Sha256() => sha256.ComputeHash(data); } - + public class IntroFluentConfigBuilder { public static void Run() diff --git a/samples/BenchmarkDotNet.Samples/IntroHardwareCounters.cs b/samples/BenchmarkDotNet.Samples/IntroHardwareCounters.cs index a5b0ee347b..771bc48a3c 100644 --- a/samples/BenchmarkDotNet.Samples/IntroHardwareCounters.cs +++ b/samples/BenchmarkDotNet.Samples/IntroHardwareCounters.cs @@ -5,7 +5,7 @@ namespace BenchmarkDotNet.Samples { [HardwareCounters( - HardwareCounter.BranchMispredictions, + HardwareCounter.BranchMispredictions, HardwareCounter.BranchInstructions)] public class IntroHardwareCounters { diff --git a/samples/BenchmarkDotNet.Samples/IntroJobBaseline.cs b/samples/BenchmarkDotNet.Samples/IntroJobBaseline.cs index ce9ee92c90..e0165f587c 100644 --- a/samples/BenchmarkDotNet.Samples/IntroJobBaseline.cs +++ b/samples/BenchmarkDotNet.Samples/IntroJobBaseline.cs @@ -9,7 +9,7 @@ namespace BenchmarkDotNet.Samples public class IntroJobBaseline { [Benchmark] - public int SplitJoin() + public int SplitJoin() => string.Join(",", new string[1000]).Split(',').Length; } } \ No newline at end of file diff --git a/samples/BenchmarkDotNet.Samples/IntroJoin.cs b/samples/BenchmarkDotNet.Samples/IntroJoin.cs index d74f0fd42c..8c895bba42 100644 --- a/samples/BenchmarkDotNet.Samples/IntroJoin.cs +++ b/samples/BenchmarkDotNet.Samples/IntroJoin.cs @@ -4,14 +4,14 @@ namespace BenchmarkDotNet.Samples { // Run BenchmarkSwitcher with arguments: "--join --category=IntroJoinA" - + [DryJob] public class IntroJoin1 { [Benchmark] [BenchmarkCategory("IntroJoinA")] public void A() => Thread.Sleep(10); - + [Benchmark] [BenchmarkCategory("IntroJoinB")] public void B() => Thread.Sleep(10); @@ -23,7 +23,7 @@ public class IntroJoin2 [Benchmark] [BenchmarkCategory("IntroJoinA")] public void A() => Thread.Sleep(10); - + [Benchmark] [BenchmarkCategory("IntroJoinB")] public void B() => Thread.Sleep(10); diff --git a/samples/BenchmarkDotNet.Samples/IntroMultimodal.cs b/samples/BenchmarkDotNet.Samples/IntroMultimodal.cs index 45b4660439..9cad65e36a 100644 --- a/samples/BenchmarkDotNet.Samples/IntroMultimodal.cs +++ b/samples/BenchmarkDotNet.Samples/IntroMultimodal.cs @@ -11,7 +11,7 @@ public class IntroMultimodal { private readonly Random rnd = new Random(42); - private void Multimodal(int n) + private void Multimodal(int n) => Thread.Sleep((rnd.Next(n) + 1) * 100); [Benchmark] public void Unimodal() => Multimodal(1); diff --git a/samples/BenchmarkDotNet.Samples/IntroNuGet.cs b/samples/BenchmarkDotNet.Samples/IntroNuGet.cs index aefd6f7982..0b34868dcb 100644 --- a/samples/BenchmarkDotNet.Samples/IntroNuGet.cs +++ b/samples/BenchmarkDotNet.Samples/IntroNuGet.cs @@ -16,7 +16,7 @@ namespace BenchmarkDotNet.Samples public class IntroNuGet { // Specify jobs with different versions of the same NuGet package to benchmark. - // The NuGet versions referenced on these jobs must be greater or equal to the + // The NuGet versions referenced on these jobs must be greater or equal to the // same NuGet version referenced in this benchmark project. // Example: This benchmark project references Newtonsoft.Json 9.0.1 private class Config : ManualConfig diff --git a/samples/BenchmarkDotNet.Samples/IntroOrderManual.cs b/samples/BenchmarkDotNet.Samples/IntroOrderManual.cs index a2a5ac8bc5..7f0d7e5db5 100644 --- a/samples/BenchmarkDotNet.Samples/IntroOrderManual.cs +++ b/samples/BenchmarkDotNet.Samples/IntroOrderManual.cs @@ -37,7 +37,7 @@ orderby summary[benchmark].ResultStatistics.Mean public string GetLogicalGroupKey(ImmutableArray allBenchmarksCases, BenchmarkCase benchmarkCase) => benchmarkCase.Job.DisplayInfo + "_" + benchmarkCase.Parameters.DisplayInfo; - public IEnumerable> GetLogicalGroupOrder(IEnumerable> logicalGroups) => + public IEnumerable> GetLogicalGroupOrder(IEnumerable> logicalGroups) => logicalGroups.OrderBy(it => it.Key); public bool SeparateLogicalGroups => true; diff --git a/samples/BenchmarkDotNet.Samples/IntroSetupCleanupGlobal.cs b/samples/BenchmarkDotNet.Samples/IntroSetupCleanupGlobal.cs index d37e0cce8a..731fd889c9 100644 --- a/samples/BenchmarkDotNet.Samples/IntroSetupCleanupGlobal.cs +++ b/samples/BenchmarkDotNet.Samples/IntroSetupCleanupGlobal.cs @@ -14,7 +14,7 @@ public void GlobalSetup() { data = new int[N]; // executed once per each N value } - + [Benchmark] public int Logic() { @@ -23,7 +23,7 @@ public int Logic() res += data[i]; return res; } - + [GlobalCleanup] public void GlobalCleanup() { diff --git a/samples/BenchmarkDotNet.Samples/IntroSetupCleanupTarget.cs b/samples/BenchmarkDotNet.Samples/IntroSetupCleanupTarget.cs index d9300381bb..f684fe6408 100644 --- a/samples/BenchmarkDotNet.Samples/IntroSetupCleanupTarget.cs +++ b/samples/BenchmarkDotNet.Samples/IntroSetupCleanupTarget.cs @@ -4,16 +4,16 @@ namespace BenchmarkDotNet.Samples { - [SimpleJob(RunStrategy.Monitoring, launchCount: 0, + [SimpleJob(RunStrategy.Monitoring, launchCount: 0, warmupCount: 0, targetCount: 1)] public class IntroSetupCleanupTarget { [GlobalSetup(Target = nameof(BenchmarkA))] - public void GlobalSetupA() + public void GlobalSetupA() => Console.WriteLine("// " + "GlobalSetup A"); [Benchmark] - public void BenchmarkA() + public void BenchmarkA() => Console.WriteLine("// " + "Benchmark A"); [GlobalSetup(Targets = new[] { nameof(BenchmarkB), nameof(BenchmarkC) })] @@ -21,15 +21,15 @@ public void GlobalSetupB() => Console.WriteLine("// " + "GlobalSetup B"); [Benchmark] - public void BenchmarkB() + public void BenchmarkB() => Console.WriteLine("// " + "Benchmark B"); [Benchmark] - public void BenchmarkC() + public void BenchmarkC() => Console.WriteLine("// " + "Benchmark C"); [Benchmark] - public void BenchmarkD() + public void BenchmarkD() => Console.WriteLine("// " + "Benchmark D"); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet.Annotations/Attributes/GlobalCleanupAttribute.cs b/src/BenchmarkDotNet.Annotations/Attributes/GlobalCleanupAttribute.cs index 04dca994d0..e875871404 100644 --- a/src/BenchmarkDotNet.Annotations/Attributes/GlobalCleanupAttribute.cs +++ b/src/BenchmarkDotNet.Annotations/Attributes/GlobalCleanupAttribute.cs @@ -8,7 +8,7 @@ namespace BenchmarkDotNet.Attributes /// It's going to be executed only once, after all benchmark runs. /// [AttributeUsage(AttributeTargets.Method)] - [MeansImplicitUse] + [MeansImplicitUse] public class GlobalCleanupAttribute : TargetedAttribute { } diff --git a/src/BenchmarkDotNet.Annotations/Attributes/ParamsAttribute.cs b/src/BenchmarkDotNet.Annotations/Attributes/ParamsAttribute.cs index 946202a917..e541a9c4a7 100644 --- a/src/BenchmarkDotNet.Annotations/Attributes/ParamsAttribute.cs +++ b/src/BenchmarkDotNet.Annotations/Attributes/ParamsAttribute.cs @@ -10,7 +10,7 @@ public class ParamsAttribute : Attribute // CLS-Compliant Code requires a constructor without an array in the argument list public ParamsAttribute() => Values = new object[0]; - public ParamsAttribute(params object[] values) + public ParamsAttribute(params object[] values) => Values = values ?? new object[] { null }; // when users do Params(null) they mean one, null argument } } diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/ConcurrencyVisualizerProfiler.cs b/src/BenchmarkDotNet.Diagnostics.Windows/ConcurrencyVisualizerProfiler.cs index 9870704ebb..acb6280162 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/ConcurrencyVisualizerProfiler.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/ConcurrencyVisualizerProfiler.cs @@ -54,7 +54,7 @@ public void DisplayResults(ILogger logger) { if (!benchmarkToCvTraceFile.Any()) return; - + logger.WriteLineInfo($"Exported {benchmarkToCvTraceFile.Count} CV trace file(s). Example:"); logger.WriteLineInfo(benchmarkToCvTraceFile.Values.First()); logger.WriteLineInfo("DO remember that this Diagnoser just tries to mimic the CVCollectionCmd.exe and you need to have Visual Studio with Concurrency Visualizer plugin installed to visualize the data."); @@ -80,7 +80,7 @@ public void Handle(HostSignal signal, DiagnoserActionParameters parameters) private static EtwProfilerConfig CreateDefaultConfig() { var kernelKeywords = KernelTraceEventParser.Keywords.ImageLoad | KernelTraceEventParser.Keywords.Profile; // same as for EtwProfiler - + // following keywords come from decompiled "GetLocalTraceProviders" of CVCollectionService.exe // we don't use KernelTraceEventParser.Keywords.Dispatcher because it blows the CV Visualizer in VS, same goes for KernelTraceEventParser.Keywords.ThreadTime which I tried to experiment with kernelKeywords |= KernelTraceEventParser.Keywords.Process | KernelTraceEventParser.Keywords.Thread | KernelTraceEventParser.Keywords.ContextSwitch; @@ -111,7 +111,7 @@ private static EtwProfilerConfig CreateDefaultConfig() | ClrTraceEventParser.Keywords.ThreadTransfer), // extra new TraceEventProviderOptions { StacksEnabled = false }) // stacks are too expensive for our purposes }; - + return new EtwProfilerConfig( performExtraBenchmarksRun: false, kernelKeywords: kernelKeywords, @@ -126,8 +126,8 @@ private string CreateCvTraceFile(DiagnoserActionParameters parameters) var directoryPath = Path.GetDirectoryName(traceFilePath); var cvPathFile = Path.ChangeExtension(traceFilePath, ".CvTrace"); var traceFileName = Path.GetFileName(traceFilePath); - - File.WriteAllText(cvPathFile, + + File.WriteAllText(cvPathFile, $@" diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/EtwDiagnoser.cs b/src/BenchmarkDotNet.Diagnostics.Windows/EtwDiagnoser.cs index f73ca0bbe9..42ec98ac40 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/EtwDiagnoser.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/EtwDiagnoser.cs @@ -42,7 +42,7 @@ protected void Start(DiagnoserActionParameters parameters) // This is in effect the inverted sequence of actions in the Stop() method. Console.CancelKeyPress += OnConsoleCancelKeyPress; AppDomain.CurrentDomain.ProcessExit += OnProcessExit; - + Session = CreateSession(parameters.BenchmarkCase); EnableProvider(); @@ -56,7 +56,7 @@ protected void Start(DiagnoserActionParameters parameters) // and through the TraceEventSession class, which is thread-safe. var task = Task.Factory.StartNew((Action)(() => Session.Source.Process()), TaskCreationOptions.LongRunning); - // wait until the processing has started, block by then so we don't loose any + // wait until the processing has started, block by then so we don't loose any // information (very important for jit-related things) WaitUntilStarted(task); } diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/HardwareCounters.cs b/src/BenchmarkDotNet.Diagnostics.Windows/HardwareCounters.cs index 5de055b37c..3564c639ae 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/HardwareCounters.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/HardwareCounters.cs @@ -30,7 +30,7 @@ private static readonly Dictionary EtwTranslations { HardwareCounter.BranchInstructionRetired, "BranchInstructionRetired" }, { HardwareCounter.BranchMispredictsRetired, "BranchMispredictsRetired" } }; - + public static IEnumerable Validate(ValidationParameters validationParameters, bool mandatory) { if (!RuntimeInformation.IsWindows()) @@ -38,7 +38,7 @@ public static IEnumerable Validate(ValidationParameters validat yield return new ValidationError(true, "Hardware Counters and EtwProfiler are supported only on Windows"); yield break; } - + if (!validationParameters.Config.GetHardwareCounters().Any() && mandatory) { yield return new ValidationError(true, "No Hardware Counters defined, probably a bug"); diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs b/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs index b98dc026ed..605951f962 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs @@ -55,7 +55,7 @@ protected override void AttachToEvents(TraceEventSession session, BenchmarkCase session.Source.Clr.MethodInliningSucceeded += jitData => { // Inliner = the parent method (the inliner calls the inlinee) - // Inlinee = the method that is going to be "inlined" inside the inliner (it's caller) + // Inlinee = the method that is going to be "inlined" inside the inliner (it's caller) if (StatsPerProcess.TryGetValue(jitData.ProcessID, out _)) { var shouldPrint = !logFailuresOnly @@ -96,10 +96,10 @@ protected override void AttachToEvents(TraceEventSession session, BenchmarkCase } }; } - + private bool ShouldPrintEventInfo(string inlinerNamespace, string inlineeNamespace) - => !filterByNamespace || - (allowedNamespaces?.Any(x=> inlineeNamespace.StartsWith(x) || inlinerNamespace.StartsWith(x)) + => !filterByNamespace || + (allowedNamespaces?.Any(x=> inlineeNamespace.StartsWith(x) || inlinerNamespace.StartsWith(x)) ?? (inlinerNamespace.StartsWith(defaultNamespace)) || inlineeNamespace.StartsWith(defaultNamespace)); } } diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/PmcDiagnoser.cs b/src/BenchmarkDotNet.Diagnostics.Windows/PmcDiagnoser.cs index b4b6c80a69..66770dc369 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/PmcDiagnoser.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/PmcDiagnoser.cs @@ -59,7 +59,7 @@ public IEnumerable Validate(ValidationParameters validationPara protected override PmcStats GetInitializedStats(DiagnoserActionParameters parameters) { var stats = new PmcStats( - parameters.Config.GetHardwareCounters().ToArray(), + parameters.Config.GetHardwareCounters().ToArray(), counter => HardwareCounters.FromCounter(counter, info => info.MinInterval )); // for this diagnoser we want the smallest interval to have best possible precision HardwareCounters.Enable(stats.Counters.Values); diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/IterationEvent.cs b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/IterationEvent.cs index 2adc914f5b..7908f7cf52 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/IterationEvent.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/IterationEvent.cs @@ -8,7 +8,7 @@ namespace BenchmarkDotNet.Diagnostics.Windows.Tracing public sealed class IterationEvent : TraceEvent { public long TotalOperations => GetInt64At(0); - + private event Action target; internal IterationEvent(Action target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) @@ -30,7 +30,7 @@ public override StringBuilder ToXml(StringBuilder sb) Prefix(sb); XmlAttrib(sb, nameof(TotalOperations), TotalOperations); sb.Append("/>"); - + return sb; } diff --git a/src/BenchmarkDotNet/Analysers/AnalyserBase.cs b/src/BenchmarkDotNet/Analysers/AnalyserBase.cs index f9d2cc0a61..ee9943dd37 100644 --- a/src/BenchmarkDotNet/Analysers/AnalyserBase.cs +++ b/src/BenchmarkDotNet/Analysers/AnalyserBase.cs @@ -21,11 +21,11 @@ public IEnumerable Analyse(Summary summary) [PublicAPI] protected virtual IEnumerable AnalyseSummary(Summary summary) => Enumerable.Empty(); [PublicAPI] protected virtual IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) => Enumerable.Empty(); - protected Conclusion CreateHint(string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) + protected Conclusion CreateHint(string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) => Conclusion.CreateHint(Id, message, report, mergeable); - protected Conclusion CreateWarning(string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) + protected Conclusion CreateWarning(string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) => Conclusion.CreateWarning(Id, message, report, mergeable); - protected Conclusion CreateError(string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) + protected Conclusion CreateError(string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) => Conclusion.CreateError(Id, message, report, mergeable); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Analysers/Conclusion.cs b/src/BenchmarkDotNet/Analysers/Conclusion.cs index 9fb0754e12..c194ca4be8 100644 --- a/src/BenchmarkDotNet/Analysers/Conclusion.cs +++ b/src/BenchmarkDotNet/Analysers/Conclusion.cs @@ -12,7 +12,7 @@ public sealed class Conclusion : IEquatable public string AnalyserId { get; } public ConclusionKind Kind { get; } - + public bool Mergeable { get; } [NotNull] @@ -21,10 +21,10 @@ public sealed class Conclusion : IEquatable [CanBeNull] public BenchmarkReport Report { get; } - private Conclusion([NotNull] string analyserId, - ConclusionKind kind, - [NotNull] string message, - [CanBeNull] BenchmarkReport report, + private Conclusion([NotNull] string analyserId, + ConclusionKind kind, + [NotNull] string message, + [CanBeNull] BenchmarkReport report, bool mergeable) { AnalyserId = analyserId; @@ -34,13 +34,13 @@ private Conclusion([NotNull] string analyserId, Mergeable = mergeable; } - public static Conclusion CreateHint(string analyserId, string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) + public static Conclusion CreateHint(string analyserId, string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) => new Conclusion(analyserId, ConclusionKind.Hint, message, report, mergeable); - public static Conclusion CreateWarning(string analyserId, string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) + public static Conclusion CreateWarning(string analyserId, string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) => new Conclusion(analyserId, ConclusionKind.Warning, message, report, mergeable); - public static Conclusion CreateError(string analyserId, string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) + public static Conclusion CreateError(string analyserId, string message, [CanBeNull] BenchmarkReport report = null, bool mergeable = true) => new Conclusion(analyserId, ConclusionKind.Error, message, report, mergeable); public bool Equals(Conclusion other) diff --git a/src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs b/src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs index 08aeb824eb..2655ee38ed 100644 --- a/src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs +++ b/src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs @@ -20,7 +20,7 @@ protected override IEnumerable AnalyseReport(BenchmarkReport report, var statistics = report.ResultStatistics; if (statistics == null || statistics.N < EngineResolver.DefaultMinWorkloadIterationCount) yield break; - + double mValue = MathHelper.CalculateMValue(statistics); if (mValue > 4.2) yield return Create("is multimodal", mValue, report); diff --git a/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs b/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs index 818d5e6fc5..de6385509c 100644 --- a/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs @@ -21,7 +21,7 @@ protected override IEnumerable AnalyseReport(BenchmarkReport report, if (workloadActual.IsEmpty()) yield break; var result = report.AllMeasurements.Where(m => m.Is(IterationMode.Workload, IterationStage.Result)).ToArray(); - var outlierMode = report.BenchmarkCase.Job.ResolveValue(AccuracyMode.OutlierModeCharacteristic, EngineResolver.Instance); // TODO: improve + var outlierMode = report.BenchmarkCase.Job.ResolveValue(AccuracyMode.OutlierModeCharacteristic, EngineResolver.Instance); // TODO: improve var statistics = workloadActual.GetStatistics(); var allOutliers = statistics.AllOutliers; var actualOutliers = statistics.GetActualOutliers(outlierMode); diff --git a/src/BenchmarkDotNet/Analysers/ZeroMeasurementAnalyser.cs b/src/BenchmarkDotNet/Analysers/ZeroMeasurementAnalyser.cs index 01fa3a9dd8..1bb7607f10 100644 --- a/src/BenchmarkDotNet/Analysers/ZeroMeasurementAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/ZeroMeasurementAnalyser.cs @@ -5,16 +5,16 @@ using BenchmarkDotNet.Horology; using BenchmarkDotNet.Reports; -namespace BenchmarkDotNet.Analysers +namespace BenchmarkDotNet.Analysers { - public class ZeroMeasurementAnalyser : AnalyserBase + public class ZeroMeasurementAnalyser : AnalyserBase { public override string Id => "ZeroMeasurement"; - + public static readonly IAnalyser Default = new ZeroMeasurementAnalyser(); private static readonly TimeInterval FallbackCpuResolutionValue = TimeInterval.FromNanoseconds(0.2d); - + private ZeroMeasurementAnalyser() { } protected override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) @@ -29,13 +29,13 @@ protected override IEnumerable AnalyseReport(BenchmarkReport report, if (workloadMeasurements.IsEmpty()) yield break; var workload = workloadMeasurements.GetStatistics(); - + var threshold = currentFrequency.Value.ToResolution().Nanoseconds / 2; var zeroMeasurement = overheadMeasurements.Any() ? ZeroMeasurementHelper.CheckZeroMeasurementTwoSamples(workload.WithoutOutliers(), overheadMeasurements.GetStatistics().WithoutOutliers()) : ZeroMeasurementHelper.CheckZeroMeasurementOneSample(workload.WithoutOutliers(), threshold); - + if (zeroMeasurement) yield return CreateWarning("The method duration is indistinguishable from the empty method duration", report, false); diff --git a/src/BenchmarkDotNet/Attributes/Columns/ColumnConfigBaseAttribute.cs b/src/BenchmarkDotNet/Attributes/Columns/ColumnConfigBaseAttribute.cs index aef7198cc0..ab4c3aa9a8 100644 --- a/src/BenchmarkDotNet/Attributes/Columns/ColumnConfigBaseAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Columns/ColumnConfigBaseAttribute.cs @@ -4,7 +4,7 @@ using JetBrains.Annotations; namespace BenchmarkDotNet.Attributes -{ +{ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)] public abstract class ColumnConfigBaseAttribute : Attribute, IConfigSource { diff --git a/src/BenchmarkDotNet/Attributes/Columns/WelchTTestPValueColumnAttribute.cs b/src/BenchmarkDotNet/Attributes/Columns/WelchTTestPValueColumnAttribute.cs index 99947ec493..55950f2e10 100644 --- a/src/BenchmarkDotNet/Attributes/Columns/WelchTTestPValueColumnAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Columns/WelchTTestPValueColumnAttribute.cs @@ -13,7 +13,7 @@ public StatisticalTestColumnAttribute(StatisticalTestKind testKind, ThresholdUni : base(StatisticalTestColumn.Create(testKind, Threshold.Create(thresholdUnit, value), showPValues)) { } public StatisticalTestColumnAttribute(StatisticalTestKind testKind, bool showPValues = false) : this(testKind, ThresholdUnit.Ratio, 0.1, showPValues) { } - + public StatisticalTestColumnAttribute(bool showPValues = false) : this(StatisticalTestKind.MannWhitney, showPValues) {} } diff --git a/src/BenchmarkDotNet/Attributes/EncodingAttribute.cs b/src/BenchmarkDotNet/Attributes/EncodingAttribute.cs index 411cbb2f53..b5d0ebc30c 100644 --- a/src/BenchmarkDotNet/Attributes/EncodingAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/EncodingAttribute.cs @@ -18,7 +18,7 @@ public class Unicode: EncodingAttribute { public Unicode() : base(Encoding.Unicode) { } } - + [PublicAPI] public class ASCII: EncodingAttribute { diff --git a/src/BenchmarkDotNet/Attributes/Filters/AllCategoriesFilterAttribute.cs b/src/BenchmarkDotNet/Attributes/Filters/AllCategoriesFilterAttribute.cs index 0edf44a9cf..8560f0cb10 100644 --- a/src/BenchmarkDotNet/Attributes/Filters/AllCategoriesFilterAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Filters/AllCategoriesFilterAttribute.cs @@ -8,7 +8,7 @@ public class AllCategoriesFilterAttribute : FilterConfigBaseAttribute { // CLS-Compliant Code requires a constructor without an array in the argument list public AllCategoriesFilterAttribute() { } - + public AllCategoriesFilterAttribute(params string[] targetCategories) : base(new AllCategoriesFilter(targetCategories)) { } } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Attributes/Filters/AnyCategoriesFilterAttribute.cs b/src/BenchmarkDotNet/Attributes/Filters/AnyCategoriesFilterAttribute.cs index 20734ccd2e..b7020b3909 100644 --- a/src/BenchmarkDotNet/Attributes/Filters/AnyCategoriesFilterAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Filters/AnyCategoriesFilterAttribute.cs @@ -8,7 +8,7 @@ public class AnyCategoriesFilterAttribute : FilterConfigBaseAttribute // CLS-Compliant Code requires a constructor without an array in the argument list [PublicAPI] public AnyCategoriesFilterAttribute() { } - + public AnyCategoriesFilterAttribute(params string[] targetCategories) : base(new AnyCategoriesFilter(targetCategories)) { } } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Attributes/Filters/FilterConfigBaseAttribute.cs b/src/BenchmarkDotNet/Attributes/Filters/FilterConfigBaseAttribute.cs index aa07914ca9..2b9c6e400e 100644 --- a/src/BenchmarkDotNet/Attributes/Filters/FilterConfigBaseAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Filters/FilterConfigBaseAttribute.cs @@ -3,7 +3,7 @@ using BenchmarkDotNet.Filters; namespace BenchmarkDotNet.Attributes -{ +{ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)] public abstract class FilterConfigBaseAttribute : Attribute, IConfigSource { diff --git a/src/BenchmarkDotNet/Attributes/GroupBenchmarksByAttribute.cs b/src/BenchmarkDotNet/Attributes/GroupBenchmarksByAttribute.cs index bfc337d3d1..d542a89c98 100644 --- a/src/BenchmarkDotNet/Attributes/GroupBenchmarksByAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/GroupBenchmarksByAttribute.cs @@ -15,7 +15,7 @@ protected GroupBenchmarksByAttribute() { Config = ManualConfig.CreateEmpty(); } - + public GroupBenchmarksByAttribute(params BenchmarkLogicalGroupRule[] rules) { Config = ManualConfig.CreateEmpty().With(rules); diff --git a/src/BenchmarkDotNet/Attributes/Jobs/MonoJobAttribute.cs b/src/BenchmarkDotNet/Attributes/Jobs/MonoJobAttribute.cs index 7646d1d996..965930a5bb 100644 --- a/src/BenchmarkDotNet/Attributes/Jobs/MonoJobAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Jobs/MonoJobAttribute.cs @@ -11,7 +11,7 @@ public MonoJobAttribute(bool baseline = false) : base(Job.Default.With(MonoRunti { } - public MonoJobAttribute(string name, string path, bool baseline = false) + public MonoJobAttribute(string name, string path, bool baseline = false) : base(new Job(name, new EnvironmentMode(new MonoRuntime(name, path)).Freeze()).WithBaseline(baseline).Freeze()) { } diff --git a/src/BenchmarkDotNet/Attributes/Mutators/InnerIterationCountAttribute.cs b/src/BenchmarkDotNet/Attributes/Mutators/InnerIterationCountAttribute.cs index 1ea6deaf69..f103f7b0b0 100644 --- a/src/BenchmarkDotNet/Attributes/Mutators/InnerIterationCountAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Mutators/InnerIterationCountAttribute.cs @@ -10,7 +10,7 @@ namespace BenchmarkDotNet.Attributes [PublicAPI] public class InnerIterationCountAttribute : JobMutatorConfigBaseAttribute { - public InnerIterationCountAttribute(int invocationCount) + public InnerIterationCountAttribute(int invocationCount) : base(Job.Default .WithInvocationCount(invocationCount) .WithUnrollFactor(1)) // it's for xunit-performance porting purpose, where the idea of unroll factor did not exist diff --git a/src/BenchmarkDotNet/Attributes/Mutators/JobMutatorConfigBaseAttribute.cs b/src/BenchmarkDotNet/Attributes/Mutators/JobMutatorConfigBaseAttribute.cs index 8a18fefa60..f59b4b5c52 100644 --- a/src/BenchmarkDotNet/Attributes/Mutators/JobMutatorConfigBaseAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Mutators/JobMutatorConfigBaseAttribute.cs @@ -11,9 +11,9 @@ public class JobMutatorConfigBaseAttribute : Attribute, IConfigSource // CLS-Compliant Code requires a constructor which use only CLS-compliant types [PublicAPI] public JobMutatorConfigBaseAttribute() => Config = ManualConfig.CreateEmpty(); - + protected JobMutatorConfigBaseAttribute(Job job) => Config = ManualConfig.CreateEmpty().With(job.AsMutator()); - + public IConfig Config { get; } } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Attributes/Mutators/MaxWarmupCountAttribute.cs b/src/BenchmarkDotNet/Attributes/Mutators/MaxWarmupCountAttribute.cs index 72f32fd5b7..ae4c88a25a 100644 --- a/src/BenchmarkDotNet/Attributes/Mutators/MaxWarmupCountAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Mutators/MaxWarmupCountAttribute.cs @@ -11,9 +11,9 @@ public class MaxWarmupCountAttribute : JobMutatorConfigBaseAttribute { /// Maximum count of warmup iterations that should be performed. The default value is 50 /// if set to true, will overwrite WarmupCount of the global config - public MaxWarmupCountAttribute(int maxWarmupCount, bool forceAutoWarmup = false) - : base(forceAutoWarmup - ? Job.Default.WithMaxWarmupCount(maxWarmupCount).WithWarmupCount(EngineResolver.ForceAutoWarmup) + public MaxWarmupCountAttribute(int maxWarmupCount, bool forceAutoWarmup = false) + : base(forceAutoWarmup + ? Job.Default.WithMaxWarmupCount(maxWarmupCount).WithWarmupCount(EngineResolver.ForceAutoWarmup) : Job.Default.WithMaxWarmupCount(maxWarmupCount)) { } diff --git a/src/BenchmarkDotNet/Attributes/Mutators/MinWarmupCountAttribute.cs b/src/BenchmarkDotNet/Attributes/Mutators/MinWarmupCountAttribute.cs index 2f7114cac8..4229753bdb 100644 --- a/src/BenchmarkDotNet/Attributes/Mutators/MinWarmupCountAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Mutators/MinWarmupCountAttribute.cs @@ -11,9 +11,9 @@ public class MinWarmupCountAttribute : JobMutatorConfigBaseAttribute { /// Minimum count of warmup iterations that should be performed. The default value is 6 /// if set to true, will overwrite WarmupCount in the global config - public MinWarmupCountAttribute(int minWarmupCount, bool forceAutoWarmup = false) - : base(forceAutoWarmup - ? Job.Default.WithMinWarmupCount(minWarmupCount).WithWarmupCount(EngineResolver.ForceAutoWarmup) + public MinWarmupCountAttribute(int minWarmupCount, bool forceAutoWarmup = false) + : base(forceAutoWarmup + ? Job.Default.WithMinWarmupCount(minWarmupCount).WithWarmupCount(EngineResolver.ForceAutoWarmup) : Job.Default.WithMinWarmupCount(minWarmupCount)) { } diff --git a/src/BenchmarkDotNet/Attributes/Mutators/WarmupCountAttribute.cs b/src/BenchmarkDotNet/Attributes/Mutators/WarmupCountAttribute.cs index a856289e53..d5ebbfef64 100644 --- a/src/BenchmarkDotNet/Attributes/Mutators/WarmupCountAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Mutators/WarmupCountAttribute.cs @@ -1,7 +1,7 @@ using BenchmarkDotNet.Jobs; using JetBrains.Annotations; -namespace BenchmarkDotNet.Attributes +namespace BenchmarkDotNet.Attributes { /// /// How many warmup iterations should be performed. diff --git a/src/BenchmarkDotNet/Attributes/OrdererAttribute.cs b/src/BenchmarkDotNet/Attributes/OrdererAttribute.cs index 2a9cc57409..66da5ba8e0 100644 --- a/src/BenchmarkDotNet/Attributes/OrdererAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/OrdererAttribute.cs @@ -8,7 +8,7 @@ namespace BenchmarkDotNet.Attributes public class OrdererAttribute : Attribute, IConfigSource { public OrdererAttribute( - SummaryOrderPolicy summaryOrderPolicy = SummaryOrderPolicy.Default, + SummaryOrderPolicy summaryOrderPolicy = SummaryOrderPolicy.Default, MethodOrderPolicy methodOrderPolicy = MethodOrderPolicy.Declared) { Config = ManualConfig.CreateEmpty().With(new DefaultOrderer(summaryOrderPolicy, methodOrderPolicy)); diff --git a/src/BenchmarkDotNet/Attributes/StopOnFirstErrorAttribute.cs b/src/BenchmarkDotNet/Attributes/StopOnFirstErrorAttribute.cs index 8862af2d2e..caef5071fc 100644 --- a/src/BenchmarkDotNet/Attributes/StopOnFirstErrorAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/StopOnFirstErrorAttribute.cs @@ -2,7 +2,7 @@ using BenchmarkDotNet.Configs; using JetBrains.Annotations; -namespace BenchmarkDotNet.Attributes +namespace BenchmarkDotNet.Attributes { /// /// determines if running should be stop after first error diff --git a/src/BenchmarkDotNet/Characteristics/Characteristic.cs b/src/BenchmarkDotNet/Characteristics/Characteristic.cs index b83aad315a..7b4c556d4a 100644 --- a/src/BenchmarkDotNet/Characteristics/Characteristic.cs +++ b/src/BenchmarkDotNet/Characteristics/Characteristic.cs @@ -8,7 +8,7 @@ public abstract class Characteristic public static readonly object EmptyValue = new object(); public static Characteristic Create(string memberName) - where TOwner : CharacteristicObject + where TOwner : CharacteristicObject => new Characteristic( memberName, typeof(TOwner), @@ -16,15 +16,15 @@ public static Characteristic Create(string memberName) false); public static Characteristic Create(string memberName, T fallbackValue) - where TOwner : CharacteristicObject + where TOwner : CharacteristicObject => new Characteristic( - memberName, + memberName, typeof(TOwner), null, fallbackValue, false); public static Characteristic Create(string memberName, Func resolver, T fallbackValue, bool ignoreOnApply) - where TOwner : CharacteristicObject + where TOwner : CharacteristicObject => new Characteristic( memberName, typeof(TOwner), @@ -32,15 +32,15 @@ public static Characteristic Create(string memberName, Func CreateHidden(string memberName) - where TOwner : CharacteristicObject + where TOwner : CharacteristicObject => new Characteristic( memberName, typeof(TOwner), null, default, false, true); - + public static Characteristic CreateIgnoreOnApply(string memberName) - where TOwner : CharacteristicObject + where TOwner : CharacteristicObject => new Characteristic( memberName, typeof(TOwner), @@ -75,7 +75,7 @@ protected Characteristic( // TODO: better naming. As it is for now this property used for Id only and has meaning "if set, will not transfer to others nor be cleared". public bool IgnoreOnApply { get; } - + public bool DontShowInSummary { get; } public Type CharacteristicType { get; } diff --git a/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs b/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs index cd620fdc5a..936f6ac31b 100644 --- a/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs +++ b/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs @@ -91,7 +91,7 @@ private static void AssertIsAssignable(Characteristic characteristic, object val #endregion #region Properties - + private CharacteristicObject Owner { get; set; } protected CharacteristicObject OwnerOrSelf => Owner ?? this; @@ -315,7 +315,7 @@ private void SetValueOnAttach(Characteristic characteristic, object value) #endregion #region Apply - + [PublicAPI] public void Apply(CharacteristicObject other) => ApplyCore(other); @@ -362,7 +362,7 @@ private CharacteristicObject ApplyCore( #endregion #region Freeze / unfreeze - + [PublicAPI] public void Freeze() => FreezeCore(); diff --git a/src/BenchmarkDotNet/Characteristics/CharacteristicObject`1.cs b/src/BenchmarkDotNet/Characteristics/CharacteristicObject`1.cs index 4eef876c72..61f207daf9 100644 --- a/src/BenchmarkDotNet/Characteristics/CharacteristicObject`1.cs +++ b/src/BenchmarkDotNet/Characteristics/CharacteristicObject`1.cs @@ -33,9 +33,9 @@ public T Apply(params CharacteristicObject[] others) public new T UnfreezeCopy() => (T)UnfreezeCopyCore(); protected static Characteristic CreateCharacteristic(string memberName) => Characteristic.Create(memberName); - + protected static Characteristic CreateHiddenCharacteristic(string memberName) => Characteristic.CreateHidden(memberName); - + protected static Characteristic CreateIgnoreOnApplyCharacteristic(string memberName) => Characteristic.CreateIgnoreOnApply(memberName); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Characteristics/CharacteristicPresenter.cs b/src/BenchmarkDotNet/Characteristics/CharacteristicPresenter.cs index a079ae0e5a..4a12064795 100644 --- a/src/BenchmarkDotNet/Characteristics/CharacteristicPresenter.cs +++ b/src/BenchmarkDotNet/Characteristics/CharacteristicPresenter.cs @@ -16,14 +16,14 @@ public abstract class CharacteristicPresenter public static readonly CharacteristicPresenter SourceCodePresenter = new SourceCodeCharacteristicPresenter(); public abstract string ToPresentation(CharacteristicObject obj, Characteristic characteristic); - + public abstract string ToPresentation(object characteristicValue, Characteristic characteristic); private class DefaultCharacteristicPresenter : CharacteristicPresenter { - public override string ToPresentation(CharacteristicObject obj, Characteristic characteristic) - => obj.HasValue(characteristic) - ? ToPresentation(characteristic[obj], characteristic) + public override string ToPresentation(CharacteristicObject obj, Characteristic characteristic) + => obj.HasValue(characteristic) + ? ToPresentation(characteristic[obj], characteristic) : "Default"; public override string ToPresentation(object value, Characteristic characteristic) @@ -60,12 +60,12 @@ private static string ToPresentation(IEnumerable collection) return buffer.ToString(); } - private static string ToPresentation(object value) + private static string ToPresentation(object value) => (value as IFormattable)?.ToString(null, HostEnvironmentInfo.MainCultureInfo) ?? value?.ToString() ?? ""; - + } private class SourceCodeCharacteristicPresenter : CharacteristicPresenter @@ -85,7 +85,7 @@ public override string ToPresentation(object characteristicValue, Characteristic private class FolderCharacteristicPresenter : CharacteristicPresenter { - public override string ToPresentation(CharacteristicObject obj, Characteristic characteristic) + public override string ToPresentation(CharacteristicObject obj, Characteristic characteristic) => obj.HasValue(characteristic) ? ToPresentation(characteristic[obj], characteristic) : "Default"; diff --git a/src/BenchmarkDotNet/Characteristics/CharacteristicSetPresenter.cs b/src/BenchmarkDotNet/Characteristics/CharacteristicSetPresenter.cs index aa1808607d..ffaa5dba6c 100644 --- a/src/BenchmarkDotNet/Characteristics/CharacteristicSetPresenter.cs +++ b/src/BenchmarkDotNet/Characteristics/CharacteristicSetPresenter.cs @@ -77,7 +77,7 @@ private class SourceCodePresenter : CharacteristicSetPresenter }; public override string ToPresentation(CharacteristicObject obj) - => string.Join(Separator, + => string.Join(Separator, GetPresentableCharacteristics(obj, includeIgnoreOnApply: true) .Select(c => CharacteristicPresenter.ToPresentation(obj, c))); diff --git a/src/BenchmarkDotNet/Code/ArrayParam.cs b/src/BenchmarkDotNet/Code/ArrayParam.cs index 2bdd61be49..f1e1a70249 100644 --- a/src/BenchmarkDotNet/Code/ArrayParam.cs +++ b/src/BenchmarkDotNet/Code/ArrayParam.cs @@ -46,7 +46,7 @@ internal static IParam FromObject(object array) throw new InvalidOperationException("The argument must be an array"); if (!SourceCodeHelper.IsCompilationTimeConstant(type.GetElementType())) throw new InvalidOperationException("The argument must be an array of primitives"); - + var arrayParamType = typeof(ArrayParam<>).MakeGenericType(type.GetElementType()); var methodInfo = arrayParamType.GetMethod(nameof(ForPrimitives), BindingFlags.Public | BindingFlags.Static) diff --git a/src/BenchmarkDotNet/Code/CodeGenerator.cs b/src/BenchmarkDotNet/Code/CodeGenerator.cs index 009d6fc345..358dca7731 100644 --- a/src/BenchmarkDotNet/Code/CodeGenerator.cs +++ b/src/BenchmarkDotNet/Code/CodeGenerator.cs @@ -100,9 +100,9 @@ private static (bool, string) GetShadowCopySettings() if (benchmarkDotNetLocation != null && benchmarkDotNetLocation.IndexOf("LINQPAD", StringComparison.OrdinalIgnoreCase) >= 0) { - /* "LINQPad normally puts the compiled query into a different folder than the referenced assemblies + /* "LINQPad normally puts the compiled query into a different folder than the referenced assemblies * - this allows for optimizations to reduce file I/O, which is important in the scratchpad scenario" - * + * * so in case we detect we are running from LINQPad, we give a hint to assembly loading to search also in this folder */ @@ -217,7 +217,7 @@ private static string GetPassArguments(BenchmarkCase benchmarkCase) benchmarkCase.Descriptor.WorkloadMethod.GetParameters() .Select((parameter, index) => $"{GetParameterModifier(parameter)} arg{index}")); - private static string GetExtraAttributes(Descriptor descriptor) + private static string GetExtraAttributes(Descriptor descriptor) => descriptor.WorkloadMethod.GetCustomAttributes(false).OfType().Any() ? "[System.STAThreadAttribute]" : string.Empty; private static string GetEngineFactoryTypeName(BenchmarkCase benchmarkCase) diff --git a/src/BenchmarkDotNet/Code/DeclarationsProvider.cs b/src/BenchmarkDotNet/Code/DeclarationsProvider.cs index a184f6cfcc..6f59c96ddb 100644 --- a/src/BenchmarkDotNet/Code/DeclarationsProvider.cs +++ b/src/BenchmarkDotNet/Code/DeclarationsProvider.cs @@ -140,7 +140,7 @@ internal class TaskDeclarationsProvider : VoidDeclarationsProvider { public TaskDeclarationsProvider(Descriptor descriptor) : base(descriptor) { } - // we use GetAwaiter().GetResult() because it's fastest way to obtain the result in blocking way, + // we use GetAwaiter().GetResult() because it's fastest way to obtain the result in blocking way, // and will eventually throw actual exception, not aggregated one public override string WorkloadMethodDelegate(string passArguments) => $"({passArguments}) => {{ {Descriptor.WorkloadMethod.Name}({passArguments}).GetAwaiter().GetResult(); }}"; @@ -159,7 +159,7 @@ public GenericTaskDeclarationsProvider(Descriptor descriptor) : base(descriptor) protected override Type WorkloadMethodReturnType => Descriptor.WorkloadMethod.ReturnType.GetTypeInfo().GetGenericArguments().Single(); - // we use GetAwaiter().GetResult() because it's fastest way to obtain the result in blocking way, + // we use GetAwaiter().GetResult() because it's fastest way to obtain the result in blocking way, // and will eventually throw actual exception, not aggregated one public override string WorkloadMethodDelegate(string passArguments) => $"({passArguments}) => {{ return {Descriptor.WorkloadMethod.Name}({passArguments}).GetAwaiter().GetResult(); }}"; diff --git a/src/BenchmarkDotNet/Columns/BaselineScaledColumn.cs b/src/BenchmarkDotNet/Columns/BaselineScaledColumn.cs index 4df6439161..68c25cc2d8 100644 --- a/src/BenchmarkDotNet/Columns/BaselineScaledColumn.cs +++ b/src/BenchmarkDotNet/Columns/BaselineScaledColumn.cs @@ -8,7 +8,7 @@ namespace BenchmarkDotNet.Columns { - [Obsolete("Use BaselineRatioColumn"), PublicAPI] + [Obsolete("Use BaselineRatioColumn"), PublicAPI] public class BaselineScaledColumn : BaselineCustomColumn { public enum ScaledKind @@ -34,7 +34,7 @@ public override string ColumnName switch (Kind) { case ScaledKind.Mean: - return "Scaled"; + return "Scaled"; default: throw new NotSupportedException(); } diff --git a/src/BenchmarkDotNet/Columns/CategoriesColumn.cs b/src/BenchmarkDotNet/Columns/CategoriesColumn.cs index 4b38241b9c..f47988278d 100644 --- a/src/BenchmarkDotNet/Columns/CategoriesColumn.cs +++ b/src/BenchmarkDotNet/Columns/CategoriesColumn.cs @@ -8,7 +8,7 @@ namespace BenchmarkDotNet.Columns public class CategoriesColumn : IColumn { public static readonly IColumn Default = new CategoriesColumn(); - + public string Id => nameof(CategoriesColumn); public string ColumnName => "Categories"; public string GetValue(Summary summary, BenchmarkCase benchmarkCase) => string.Join(",", benchmarkCase.Descriptor.Categories); diff --git a/src/BenchmarkDotNet/Columns/DefaultColumnProvider.cs b/src/BenchmarkDotNet/Columns/DefaultColumnProvider.cs index d2b6ee2722..8f131c73dd 100644 --- a/src/BenchmarkDotNet/Columns/DefaultColumnProvider.cs +++ b/src/BenchmarkDotNet/Columns/DefaultColumnProvider.cs @@ -56,7 +56,7 @@ public IEnumerable GetColumns(Summary summary) yield return BaselineRatioColumn.RatioMean; var stdDevColumn = BaselineRatioColumn.RatioStdDev; var stdDevColumnValues = summary.BenchmarksCases.Select(b => stdDevColumn.GetValue(summary, b)); - + // Hide RatioSD column if values is small // TODO: rewrite and check raw values bool hide = stdDevColumnValues.All(value => value == "0.00" || value == "0.01"); @@ -79,7 +79,7 @@ public IEnumerable GetColumns(Summary summary) => summary .Distinct() .Select(name => new ParamColumn(name)); } - + private class MetricsColumnProvider : IColumnProvider { public IEnumerable GetColumns(Summary summary) => summary diff --git a/src/BenchmarkDotNet/Columns/JobCharacteristicColumn.cs b/src/BenchmarkDotNet/Columns/JobCharacteristicColumn.cs index a6b198dc25..74f7b2b8ba 100644 --- a/src/BenchmarkDotNet/Columns/JobCharacteristicColumn.cs +++ b/src/BenchmarkDotNet/Columns/JobCharacteristicColumn.cs @@ -42,7 +42,7 @@ public string GetValue(Summary summary, BenchmarkCase benchmarkCase) { if (!benchmarkCase.Job.HasValue(characteristic) && EnvironmentResolver.Instance.CanResolve(characteristic)) return Presenter.ToPresentation(benchmarkCase.Job.ResolveValue(characteristic, EnvironmentResolver.Instance), characteristic); - + return Presenter.ToPresentation(benchmarkCase.Job, characteristic); } diff --git a/src/BenchmarkDotNet/Columns/MetricColumn.cs b/src/BenchmarkDotNet/Columns/MetricColumn.cs index 21e6f8675b..58b07ae313 100644 --- a/src/BenchmarkDotNet/Columns/MetricColumn.cs +++ b/src/BenchmarkDotNet/Columns/MetricColumn.cs @@ -25,8 +25,8 @@ public class MetricColumn : IColumn public bool IsAvailable(Summary summary) => summary.Reports.Any(report => report.Metrics.ContainsKey(descriptor.Id)); public string GetValue(Summary summary, BenchmarkCase benchmarkCase) => GetValue(summary, benchmarkCase, SummaryStyle.Default); - - public string GetValue(Summary summary, BenchmarkCase benchmarkCase, SummaryStyle style) + + public string GetValue(Summary summary, BenchmarkCase benchmarkCase, SummaryStyle style) { if (!summary.HasReport(benchmarkCase) || !summary[benchmarkCase].Metrics.TryGetValue(descriptor.Id, out Metric metric) || (metric.Value == 0.0 && !style.PrintZeroValuesInContent)) return "-"; diff --git a/src/BenchmarkDotNet/Columns/RankColumn.cs b/src/BenchmarkDotNet/Columns/RankColumn.cs index e53bb109dc..29879eaa84 100644 --- a/src/BenchmarkDotNet/Columns/RankColumn.cs +++ b/src/BenchmarkDotNet/Columns/RankColumn.cs @@ -29,7 +29,7 @@ public string GetValue(Summary summary, BenchmarkCase benchmarkCase) int index = Array.IndexOf(logicalGroup, benchmarkCase); if (index == -1) return "?"; - + var ranks = RankHelper.GetRanks(logicalGroup.Select(b => summary[b].ResultStatistics).ToArray()); int rank = ranks[index]; return numeralSystem.ToPresentation(rank); diff --git a/src/BenchmarkDotNet/Columns/StatisticColumn.cs b/src/BenchmarkDotNet/Columns/StatisticColumn.cs index 7e1198d8b9..550be0ceda 100644 --- a/src/BenchmarkDotNet/Columns/StatisticColumn.cs +++ b/src/BenchmarkDotNet/Columns/StatisticColumn.cs @@ -14,7 +14,7 @@ public interface IStatisticColumn : IColumn { List GetAllValues(Summary summary, SummaryStyle style); } - + public class StatisticColumn : IStatisticColumn { private enum Priority @@ -24,7 +24,7 @@ private enum Priority Percentiles, Additional } - + public static readonly IStatisticColumn Mean = new StatisticColumn("Mean", "Arithmetic mean of all measurements", s => s.Mean, Priority.Main); @@ -65,7 +65,7 @@ private enum Priority /// public static readonly IColumn MValue = new StatisticColumn("MValue", "Modal value, see http://www.brendangregg.com/FrequencyTrails/modes.html", MathHelper.CalculateMValue, Priority.Additional, UnitType.Dimensionless); - + public static readonly IColumn Iterations = new StatisticColumn("Iterations", "Number of target iterations", s => s.N, Priority.Additional, UnitType.Dimensionless); @@ -141,7 +141,7 @@ private string Format(Summary summary, ImmutableConfig config, Statistics statis { if (statistics == null) return "NA"; - + int precision = summary.DisplayPrecisionManager.GetPrecision(style, this, parentColumn); string format = "N" + precision; diff --git a/src/BenchmarkDotNet/Configs/ConfigOptions.cs b/src/BenchmarkDotNet/Configs/ConfigOptions.cs index 53e9f5f490..c775e1d590 100644 --- a/src/BenchmarkDotNet/Configs/ConfigOptions.cs +++ b/src/BenchmarkDotNet/Configs/ConfigOptions.cs @@ -30,7 +30,7 @@ public enum ConfigOptions /// DontOverwriteResults = 1 << 4, /// - /// Determines if the log file should be disabled. + /// Determines if the log file should be disabled. /// DisableLogFile = 1 << 5 } diff --git a/src/BenchmarkDotNet/Configs/DebugConfig.cs b/src/BenchmarkDotNet/Configs/DebugConfig.cs index 204b4eaafd..fc98ccbe91 100644 --- a/src/BenchmarkDotNet/Configs/DebugConfig.cs +++ b/src/BenchmarkDotNet/Configs/DebugConfig.cs @@ -51,7 +51,7 @@ public override IEnumerable GetJobs() => new[] { Job.Default - .WithCustomBuildConfiguration("Debug") // will do `-c Debug everywhere` + .WithCustomBuildConfiguration("Debug") // will do `-c Debug everywhere` }; } diff --git a/src/BenchmarkDotNet/Configs/DefaultConfig.cs b/src/BenchmarkDotNet/Configs/DefaultConfig.cs index 185105dee8..b70533009f 100644 --- a/src/BenchmarkDotNet/Configs/DefaultConfig.cs +++ b/src/BenchmarkDotNet/Configs/DefaultConfig.cs @@ -28,7 +28,7 @@ private DefaultConfig() public IEnumerable GetExporters() { - // Now that we can specify exporters on the cmd line (e.g. "exporters=html,stackoverflow"), + // Now that we can specify exporters on the cmd line (e.g. "exporters=html,stackoverflow"), // we should have less enabled by default and then users can turn on the ones they want yield return CsvExporter.Default; yield return MarkdownExporter.GitHub; diff --git a/src/BenchmarkDotNet/Configs/IConfig.cs b/src/BenchmarkDotNet/Configs/IConfig.cs index 07c1ddf830..12d4d6b7a9 100644 --- a/src/BenchmarkDotNet/Configs/IConfig.cs +++ b/src/BenchmarkDotNet/Configs/IConfig.cs @@ -29,7 +29,7 @@ public interface IConfig [CanBeNull] IOrderer Orderer { get; } - SummaryStyle SummaryStyle { get; } + SummaryStyle SummaryStyle { get; } ConfigUnionRule UnionRule { get; } @@ -37,7 +37,7 @@ public interface IConfig /// the default value is "./BenchmarkDotNet.Artifacts" /// string ArtifactsPath { get; } - + /// /// the default value is ASCII /// diff --git a/src/BenchmarkDotNet/Configs/ImmutableConfig.cs b/src/BenchmarkDotNet/Configs/ImmutableConfig.cs index eb4ef415f3..71f5d006bc 100644 --- a/src/BenchmarkDotNet/Configs/ImmutableConfig.cs +++ b/src/BenchmarkDotNet/Configs/ImmutableConfig.cs @@ -38,13 +38,13 @@ internal ImmutableConfig( ImmutableHashSet uniqueHardwareCounters, ImmutableHashSet uniqueDiagnosers, ImmutableArray uniqueExporters, - ImmutableHashSet unqueAnalyzers, + ImmutableHashSet unqueAnalyzers, ImmutableHashSet uniqueValidators, ImmutableHashSet uniqueFilters, ImmutableHashSet uniqueRules, - ImmutableHashSet uniqueRunnableJobs, - ConfigUnionRule unionRule, - string artifactsPath, + ImmutableHashSet uniqueRunnableJobs, + ConfigUnionRule unionRule, + string artifactsPath, Encoding encoding, IOrderer orderer, SummaryStyle summaryStyle, @@ -72,7 +72,7 @@ internal ImmutableConfig( public string ArtifactsPath { get; } public Encoding Encoding { get; } public ConfigOptions Options { get; } - [NotNull] public IOrderer Orderer { get; } + [NotNull] public IOrderer Orderer { get; } public SummaryStyle SummaryStyle { get; } public IEnumerable GetColumnProviders() => columnProviders; @@ -85,7 +85,7 @@ internal ImmutableConfig( public IEnumerable GetHardwareCounters() => hardwareCounters; public IEnumerable GetFilters() => filters; public IEnumerable GetLogicalGroupRules() => rules; - + public ILogger GetCompositeLogger() => new CompositeLogger(loggers); public IExporter GetCompositeExporter() => new CompositeExporter(exporters); public IValidator GetCompositeValidator() => new CompositeValidator(validators); diff --git a/src/BenchmarkDotNet/ConsoleArguments/CommandLineOptions.cs b/src/BenchmarkDotNet/ConsoleArguments/CommandLineOptions.cs index db81e55543..55ce26af4e 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/CommandLineOptions.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/CommandLineOptions.cs @@ -34,7 +34,7 @@ public class CommandLineOptions [Option('d', "disasm", Required = false, Default = false, HelpText = "Gets disassembly of benchmarked code")] public bool UseDisassemblyDiagnoser { get; set; } - + [Option('p', "profiler", Required = false, HelpText = "Profiles benchmarked code using selected profiler. Currently the only available is \"ETW\" for Windows.")] public string Profiler { get; set; } @@ -67,7 +67,7 @@ public class CommandLineOptions [Option("join", Required = false, Default = false, HelpText = "Prints single table with results for all benchmarks")] public bool Join { get; set; } - + [Option("keepFiles", Required = false, Default = false, HelpText = "Determines if all auto-generated files should be kept or removed after running the benchmarks.")] public bool KeepBenchmarkFiles { get; set; } @@ -76,10 +76,10 @@ public class CommandLineOptions [Option("counters", Required = false, HelpText = "Hardware Counters", Separator = '+')] public IEnumerable HardwareCounters { get; set; } - + [Option("cli", Required = false, HelpText = "Path to dotnet cli (optional).")] public FileInfo CliPath { get; set; } - + [Option("packages", Required = false, HelpText = "The directory to restore packages to (optional).")] public DirectoryInfo RestorePath { get; set; } @@ -91,40 +91,40 @@ public class CommandLineOptions [Option("clrVersion", Required = false, HelpText = "Optional version of private CLR build used as the value of COMPLUS_Version env var.")] public string ClrVersion { get; set; } - + [Option("coreRtVersion", Required = false, HelpText = "Optional version of Microsoft.DotNet.ILCompiler which should be used to run with CoreRT. Example: \"1.0.0-alpha-26414-01\"")] public string CoreRtVersion { get; set; } [Option("ilcPath", Required = false, HelpText = "Optional IlcPath which should be used to run with private CoreRT build.")] public DirectoryInfo CoreRtPath { get; set; } - + [Option("launchCount", Required = false, HelpText = "How many times we should launch process with target benchmark. The default is 1.")] public int? LaunchCount { get; set; } - + [Option("warmupCount", Required = false, HelpText = "How many warmup iterations should be performed. If you set it, the minWarmupCount and maxWarmupCount are ignored. By default calculated by the heuristic.")] public int? WarmupIterationCount { get; set; } - + [Option("minWarmupCount", Required = false, HelpText = "Minimum count of warmup iterations that should be performed. The default is 6.")] public int? MinWarmupIterationCount { get; set; } - + [Option("maxWarmupCount", Required = false, HelpText = "Maximum count of warmup iterations that should be performed. The default is 50.")] public int? MaxWarmupIterationCount { get; set; } - + [Option("iterationTime", Required = false, HelpText = "Desired time of execution of an iteration in milliseconds. Used by Pilot stage to estimate the number of invocations per iteration. 500ms by default")] public int? IterationTimeInMilliseconds { get; set; } - + [Option("iterationCount", Required = false, HelpText = "How many target iterations should be performed. By default calculated by the heuristic.")] public int? IterationCount { get; set; } - + [Option("minIterationCount", Required = false, HelpText = "Minimum number of iterations to run. The default is 15.")] public int? MinIterationCount { get; set; } - + [Option("maxIterationCount", Required = false, HelpText = "Maximum number of iterations to run. The default is 100.")] public int? MaxIterationCount { get; set; } - + [Option("invocationCount", Required = false, HelpText = "Invocation count in a single iteration. By default calculated by the heuristic.")] public int? InvocationCount { get; set; } - + [Option("unrollFactor", Required = false, HelpText = "How many times the benchmark method will be invoked per one iteration of a generated loop. 16 by default")] public int? UnrollFactor { get; set; } @@ -139,7 +139,7 @@ public class CommandLineOptions [Option("list", Required = false, Default = ListBenchmarkCaseMode.Disabled, HelpText = "Prints all of the available benchmark names. Flat/Tree")] public ListBenchmarkCaseMode ListBenchmarkCaseMode { get; set; } - + [Option("disasmDepth", Required = false, Default = 1, HelpText = "Sets the recursive depth for the disassembler.")] public int DisassemblerRecursiveDepth { get; set; } @@ -151,7 +151,7 @@ public class CommandLineOptions [Option("stopOnFirstError", Required = false, Default = false, HelpText = "Stop on first error.")] public bool StopOnFirstError { get; set; } - + [Option("statisticalTest", Required = false, HelpText = "Threshold for Mann–Whitney U Test. Examples: 5%, 10ms, 100ns, 1s")] public string StatisticalTestThreshold { get; set; } @@ -184,7 +184,7 @@ public static IEnumerable Examples yield return new Example("Run selected benchmarks once per iteration", longName, new CommandLineOptions { RunOncePerIteration = true }); yield return new Example("Run selected benchmarks 100 times per iteration. Perform single warmup iteration and 5 actual workload iterations", longName, new CommandLineOptions { InvocationCount = 100, WarmupIterationCount = 1, IterationCount = 5}); yield return new Example("Run selected benchmarks 250ms per iteration. Perform from 9 to 15 iterations", longName, new CommandLineOptions { IterationTimeInMilliseconds = 250, MinIterationCount = 9, MaxIterationCount = 15}); - yield return new Example("Run MannWhitney test with relative ratio of 5% for all benchmarks for .NET Core 2.0 (base) vs .NET Core 2.1 (diff). .NET Core 2.0 will be baseline because it was provided as first.", longName, + yield return new Example("Run MannWhitney test with relative ratio of 5% for all benchmarks for .NET Core 2.0 (base) vs .NET Core 2.1 (diff). .NET Core 2.0 will be baseline because it was provided as first.", longName, new CommandLineOptions { Filters = new [] { "*"}, Runtimes = new[] { "netcoreapp2.0", "netcoreapp2.1" }, StatisticalTestThreshold = "5%" }); } } diff --git a/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs b/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs index b6ae311c29..291cc962d9 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs @@ -126,13 +126,13 @@ private static bool Validate(CommandLineOptions options, ILogger logger) logger.WriteLineError($"The provided path to CoreRun: \"{coreRunPath}\" does NOT exist. Please remember that BDN expects path to CoreRun.exe (corerun on Unix), not to Core_Root folder."); return false; } - + if (options.MonoPath.IsNotNullButDoesNotExist()) { logger.WriteLineError($"The provided {nameof(options.MonoPath)} \"{options.MonoPath}\" does NOT exist."); return false; } - + if (options.CoreRtPath.IsNotNullButDoesNotExist()) { logger.WriteLineError($"The provided {nameof(options.CoreRtPath)} \"{options.CoreRtPath}\" does NOT exist."); @@ -150,7 +150,7 @@ private static bool Validate(CommandLineOptions options, ILogger logger) logger.WriteLineError("You can't use more than 3 HardwareCounters at the same time."); return false; } - + foreach (var counterName in options.HardwareCounters) if (!Enum.TryParse(counterName, ignoreCase: true, out HardwareCounter _)) { @@ -175,12 +175,12 @@ private static IConfig CreateConfig(CommandLineOptions options, IConfig globalCo var expanded = Expand(baseJob.UnfreezeCopy(), options).ToArray(); // UnfreezeCopy ensures that each of the expanded jobs will have it's own ID if (expanded.Length > 1) expanded[0] = expanded[0].AsBaseline(); // if the user provides multiple jobs, then the first one should be a baseline - config.Add(expanded); + config.Add(expanded); if (config.GetJobs().IsEmpty() && baseJob != Job.Default) config.Add(baseJob); config.Add(options.Exporters.SelectMany(exporter => AvailableExporters[exporter]).ToArray()); - + config.Add(options.HardwareCounters .Select(counterName => (HardwareCounter)Enum.Parse(typeof(HardwareCounter), counterName, ignoreCase: true)) .ToArray()); @@ -219,7 +219,7 @@ private static IConfig CreateConfig(CommandLineOptions options, IConfig globalCo private static Job GetBaseJob(CommandLineOptions options, IConfig globalConfig) { - var baseJob = + var baseJob = globalConfig?.GetJobs().SingleOrDefault(job => job.Meta.IsDefault) // global config might define single custom Default job ?? AvailableJobs[options.BaseJob.ToLowerInvariant()]; @@ -379,7 +379,7 @@ private static Job CreateCoreJobWithCli(Job baseJob, CommandLineOptions options) => baseJob .With(CsProjCoreToolchain.From( new NetCoreAppSettings( - targetFrameworkMoniker: RuntimeInformation.GetCurrentRuntime().MsBuildMoniker, + targetFrameworkMoniker: RuntimeInformation.GetCurrentRuntime().MsBuildMoniker, customDotNetCliPath: options.CliPath?.FullName, runtimeFrameworkVersion: null, name: RuntimeInformation.GetCurrentRuntime().Name, @@ -419,7 +419,7 @@ private static string GetCoreRunToolchainDisplayName(IReadOnlyList pat return coreRunPath.FullName; var lastCommonDirectorySeparatorIndex = coreRunPath.FullName.LastIndexOf(Path.DirectorySeparatorChar, commonLongestPrefixIndex - 1); - + return coreRunPath.FullName.Substring(lastCommonDirectorySeparatorIndex); } } diff --git a/src/BenchmarkDotNet/ConsoleArguments/CorrectionsSuggester.cs b/src/BenchmarkDotNet/ConsoleArguments/CorrectionsSuggester.cs index 8cfa6d3b78..30a941814a 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/CorrectionsSuggester.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/CorrectionsSuggester.cs @@ -21,12 +21,12 @@ public CorrectionsSuggester(IReadOnlyList types) { var namesCollection = type.GetMethods() .Where(methodInfo => methodInfo.HasAttribute()) - .Select(methodInfo => $@"{(type.IsGenericType - ? type.GetDisplayName() + .Select(methodInfo => $@"{(type.IsGenericType + ? type.GetDisplayName() : type.FullName)}.{methodInfo.Name}") .ToArray(); benchmarkNames.AddRange(namesCollection); - + var names = namesCollection.Select(name => name.Split('.', '+')).SelectMany(GetAllPartialNames); possibleBenchmarkNames.AddRange(names); } @@ -38,7 +38,7 @@ public string[] SuggestFor([NotNull] string userInput) { if (userInput == null) throw new ArgumentNullException(nameof(userInput)); - + var calculator = new LevenshteinDistanceCalculator(); return possibleBenchmarkNames .Select(name => (name: name, distance: calculator.Calculate(userInput, name))) diff --git a/src/BenchmarkDotNet/ConsoleArguments/ListBenchmarks/BenchmarkCasesPrinter.cs b/src/BenchmarkDotNet/ConsoleArguments/ListBenchmarks/BenchmarkCasesPrinter.cs index 3cd3ef4ad8..14b6bafa6d 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/ListBenchmarks/BenchmarkCasesPrinter.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/ListBenchmarks/BenchmarkCasesPrinter.cs @@ -6,7 +6,7 @@ namespace BenchmarkDotNet.ConsoleArguments.ListBenchmarks internal class BenchmarkCasesPrinter : IBenchmarkCasesPrinter { private readonly IBenchmarkCasesPrinter printer; - + public BenchmarkCasesPrinter(ListBenchmarkCaseMode listBenchmarkCaseMode) { printer = listBenchmarkCaseMode == ListBenchmarkCaseMode.Tree diff --git a/src/BenchmarkDotNet/ConsoleArguments/ListBenchmarks/FlatBenchmarkCasesPrinter.cs b/src/BenchmarkDotNet/ConsoleArguments/ListBenchmarks/FlatBenchmarkCasesPrinter.cs index b2149106a7..e7d29594ca 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/ListBenchmarks/FlatBenchmarkCasesPrinter.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/ListBenchmarks/FlatBenchmarkCasesPrinter.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using BenchmarkDotNet.Loggers; -namespace BenchmarkDotNet.ConsoleArguments.ListBenchmarks +namespace BenchmarkDotNet.ConsoleArguments.ListBenchmarks { internal class FlatBenchmarkCasesPrinter : IBenchmarkCasesPrinter { diff --git a/src/BenchmarkDotNet/Diagnosers/CompositeDiagnoser.cs b/src/BenchmarkDotNet/Diagnosers/CompositeDiagnoser.cs index cdc162cafc..31110b7b12 100644 --- a/src/BenchmarkDotNet/Diagnosers/CompositeDiagnoser.cs +++ b/src/BenchmarkDotNet/Diagnosers/CompositeDiagnoser.cs @@ -19,14 +19,14 @@ public class CompositeDiagnoser : IDiagnoser public CompositeDiagnoser(ImmutableHashSet diagnosers) => this.diagnosers = diagnosers; - + public RunMode GetRunMode(BenchmarkCase benchmarkCase) => throw new InvalidOperationException("Should never be called for Composite Diagnoser"); public IEnumerable Ids => diagnosers.SelectMany(d => d.Ids); - public IEnumerable Exporters + public IEnumerable Exporters => diagnosers.SelectMany(diagnoser => diagnoser.Exporters); public IEnumerable Analysers @@ -51,7 +51,7 @@ public void DisplayResults(ILogger logger) } } - public IEnumerable Validate(ValidationParameters validationParameters) + public IEnumerable Validate(ValidationParameters validationParameters) => diagnosers.SelectMany(diagnoser => diagnoser.Validate(validationParameters)); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Diagnosers/CopiedDataContracts.cs b/src/BenchmarkDotNet/Diagnosers/CopiedDataContracts.cs index c6e9b25b69..9463ee6d14 100644 --- a/src/BenchmarkDotNet/Diagnosers/CopiedDataContracts.cs +++ b/src/BenchmarkDotNet/Diagnosers/CopiedDataContracts.cs @@ -34,7 +34,7 @@ public class Asm : Code /// The native end offset of this ASM representation /// public ulong EndAddress { get; set; } - + public uint SizeInBytes { get; set; } } diff --git a/src/BenchmarkDotNet/Diagnosers/DisassemblyPrettifier.cs b/src/BenchmarkDotNet/Diagnosers/DisassemblyPrettifier.cs index 1453fc820f..52a973fe1f 100644 --- a/src/BenchmarkDotNet/Diagnosers/DisassemblyPrettifier.cs +++ b/src/BenchmarkDotNet/Diagnosers/DisassemblyPrettifier.cs @@ -96,14 +96,14 @@ private static (Code source, string address, string byteRepresentation, string i // 00007ff7`ffbfd2e6 e80570ae5f call coreclr!MetaDataGetDispenser+0x72810 (00007ff8`5f6e42f0) // 00007ff7`ffbfd318 ffc7 inc edi // 00007ff7`ffbfd320 7cba jl 00007ff7`ffbfd2dc - // + // // so it's always something like // address byteRepresentation instruction [arguments] [extraArguments] string address = NextWord(asm.TextRepresentation, ref i); string byteRepresentation = NextWord(asm.TextRepresentation, ref i); string instruction = NextWord(asm.TextRepresentation, ref i); - // it's sth like + // it's sth like // call System_Private_CoreLib+0x577460 (00007ff8`59ae7460) // and we can not get managed method for this address if (!string.IsNullOrEmpty(asm.Comment) && asm.Comment != DisassemblerConstants.NotManagedMethod) diff --git a/src/BenchmarkDotNet/Diagnosers/MemoryDiagnoser.cs b/src/BenchmarkDotNet/Diagnosers/MemoryDiagnoser.cs index ddd09e7500..078718539b 100644 --- a/src/BenchmarkDotNet/Diagnosers/MemoryDiagnoser.cs +++ b/src/BenchmarkDotNet/Diagnosers/MemoryDiagnoser.cs @@ -14,9 +14,9 @@ namespace BenchmarkDotNet.Diagnosers public class MemoryDiagnoser : IDiagnoser { private const string DiagnoserId = nameof(MemoryDiagnoser); - + public static readonly MemoryDiagnoser Default = new MemoryDiagnoser(); - + private MemoryDiagnoser() { } // we want to have only a single instance of MemoryDiagnoser public RunMode GetRunMode(BenchmarkCase benchmarkCase) => RunMode.NoOverhead; @@ -26,7 +26,7 @@ private MemoryDiagnoser() { } // we want to have only a single instance of Memor public IEnumerable Analysers => Array.Empty(); public void DisplayResults(ILogger logger) { } public IEnumerable Validate(ValidationParameters validationParameters) => Array.Empty(); - + // the following methods are left empty on purpose // the action takes places in other process, and the values are gathered by Engine public void Handle(HostSignal signal, DiagnoserActionParameters parameters) { } @@ -42,7 +42,7 @@ public IEnumerable ProcessResults(DiagnoserResults diagnoserResults) private class AllocatedMemoryMetricDescriptor : IMetricDescriptor { internal static readonly IMetricDescriptor Instance = new AllocatedMemoryMetricDescriptor(); - + public string Id => "Allocated Memory"; public string DisplayName => "Allocated"; public string Legend => "Allocated memory per single operation (managed only, inclusive, 1KB = 1024B)"; diff --git a/src/BenchmarkDotNet/Diagnosers/MonoDisassembler.cs b/src/BenchmarkDotNet/Diagnosers/MonoDisassembler.cs index 290f14ca2f..b353efdeea 100644 --- a/src/BenchmarkDotNet/Diagnosers/MonoDisassembler.cs +++ b/src/BenchmarkDotNet/Diagnosers/MonoDisassembler.cs @@ -37,25 +37,25 @@ internal DisassemblyResult Disassemble(BenchmarkCase benchmarkCase, MonoRuntime string fqnMethod = GetMethodName(benchmarkTarget); string llvmFlag = GetLlvmFlag(benchmarkCase.Job); string exePath = benchmarkTarget.Type.GetTypeInfo().Assembly.Location; - + var environmentVariables = new Dictionary { ["MONO_VERBOSE_METHOD"] = fqnMethod }; string monoPath = mono?.CustomPath ?? "mono"; string arguments = $"--compile {fqnMethod} {llvmFlag} {exePath}"; var (exitCode, output) = ProcessHelper.RunAndReadOutputLineByLine(monoPath, arguments, environmentVariables: environmentVariables, includeErrors: true); string commandLine = $"{GetEnvironmentVariables(environmentVariables)} {monoPath} {arguments}"; - + return OutputParser.Parse(output, benchmarkTarget.WorkloadMethod.Name, commandLine); } - private static string GetEnvironmentVariables(Dictionary environmentVariables) + private static string GetEnvironmentVariables(Dictionary environmentVariables) => string.Join(" ", environmentVariables.Select(e => $"{e.Key}={e.Value}")); private static string GetMethodName(Descriptor descriptor) => $"{descriptor.Type.GetTypeInfo().Namespace}.{descriptor.Type.GetTypeInfo().Name}:{descriptor.WorkloadMethod.Name}"; // TODO: use resolver - // TODO: introduce a global helper method for LlvmFlag + // TODO: introduce a global helper method for LlvmFlag private static string GetLlvmFlag(Job job) => job.ResolveValue(EnvironmentMode.JitCharacteristic, Jit.Default) == Jit.Llvm ? "--llvm" : "--nollvm"; @@ -112,7 +112,7 @@ internal static DisassemblyResult Parse([ItemCanBeNull] IReadOnlyList in }; } - private static DisassemblyResult CreateErrorResult([ItemCanBeNull] IReadOnlyList input, + private static DisassemblyResult CreateErrorResult([ItemCanBeNull] IReadOnlyList input, string methodName, string commandLine, string message) { return new DisassemblyResult diff --git a/src/BenchmarkDotNet/Diagnosers/PmcMetricDescriptor.cs b/src/BenchmarkDotNet/Diagnosers/PmcMetricDescriptor.cs index 97ff5819e4..f459243072 100644 --- a/src/BenchmarkDotNet/Diagnosers/PmcMetricDescriptor.cs +++ b/src/BenchmarkDotNet/Diagnosers/PmcMetricDescriptor.cs @@ -12,7 +12,7 @@ internal PmcMetricDescriptor(PreciseMachineCounter counter) Legend = $"Hardware counter '{counter.Name}' per single operation"; TheGreaterTheBetter = counter.Counter.TheGreaterTheBetter(); } - + public string Id { get; } public string DisplayName { get; } public string Legend { get; } diff --git a/src/BenchmarkDotNet/Diagnosers/UnresolvedDiagnoser.cs b/src/BenchmarkDotNet/Diagnosers/UnresolvedDiagnoser.cs index 5bdd0f6231..51615997bb 100644 --- a/src/BenchmarkDotNet/Diagnosers/UnresolvedDiagnoser.cs +++ b/src/BenchmarkDotNet/Diagnosers/UnresolvedDiagnoser.cs @@ -33,8 +33,8 @@ public IEnumerable Validate(ValidationParameters validationPara private string GetErrorMessage() => $@"Unable to resolve {unresolved.Name} diagnoser using dynamic assembly loading. {(RuntimeInformation.IsFullFramework || RuntimeInformation.IsWindows() - ? "Please make sure that you have installed the latest BenchmarkDotNet.Diagnostics.Windows package. " + Environment.NewLine - + "If you are using `dotnet build` you also need to consume one of its public types to make sure that MSBuild copies it to the output directory. " + ? "Please make sure that you have installed the latest BenchmarkDotNet.Diagnostics.Windows package. " + Environment.NewLine + + "If you are using `dotnet build` you also need to consume one of its public types to make sure that MSBuild copies it to the output directory. " + "The alternative is to use `true` in your project file." : $"Please make sure that it's supported on {RuntimeInformation.GetOsVersion()}")}"; } diff --git a/src/BenchmarkDotNet/Engines/ConsoleHost.cs b/src/BenchmarkDotNet/Engines/ConsoleHost.cs index 482b99bc5b..a4107193f9 100644 --- a/src/BenchmarkDotNet/Engines/ConsoleHost.cs +++ b/src/BenchmarkDotNet/Engines/ConsoleHost.cs @@ -29,7 +29,7 @@ public void SendSignal(HostSignal hostSignal) // read the response from Parent process, make the communication blocking // I did not use Mutexes because they are not supported for Linux/MacOs for .NET Core // this solution is stupid simple and it works - string acknowledgment = inReader.ReadLine(); + string acknowledgment = inReader.ReadLine(); if(acknowledgment != Engine.Signals.Acknowledgment) throw new NotSupportedException($"Unknown Acknowledgment: {acknowledgment}"); } diff --git a/src/BenchmarkDotNet/Engines/Consumer.cs b/src/BenchmarkDotNet/Engines/Consumer.cs index d11f97f701..c433bcd805 100644 --- a/src/BenchmarkDotNet/Engines/Consumer.cs +++ b/src/BenchmarkDotNet/Engines/Consumer.cs @@ -97,7 +97,7 @@ private static readonly HashSet SupportedTypes [PublicAPI] public void Consume(T objectValue) where T : class // class constraint prevents from boxing structs => Volatile.Write(ref objectHolder, objectValue); - + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Consume(in T value) { @@ -130,7 +130,7 @@ public void Consume(in T value) else ValueTypesConsumer(value); // non-primitive value types } - + [MethodImpl(MethodImplOptions.NoInlining)] private void ValueTypesConsumer(in T _) { } diff --git a/src/BenchmarkDotNet/Engines/ConsumerExtensions.cs b/src/BenchmarkDotNet/Engines/ConsumerExtensions.cs index c2542aba01..f09e96496d 100644 --- a/src/BenchmarkDotNet/Engines/ConsumerExtensions.cs +++ b/src/BenchmarkDotNet/Engines/ConsumerExtensions.cs @@ -21,7 +21,7 @@ public static void Consume(this IEnumerable enumerable, Consumer consumer) consumer.Consume(item); } } - + /// /// executes and consumes given /// By using non-generic you pay for boxing. Use generic if you can. @@ -36,7 +36,7 @@ public static void Consume(this IQueryable queryable, Consumer consumer) consumer.Consume(item); } } - + /// /// executes and consumes given /// @@ -50,7 +50,7 @@ public static void Consume(this IEnumerable enumerable, Consumer consumer) consumer.Consume(in item); } } - + /// /// executes and consumes given /// diff --git a/src/BenchmarkDotNet/Engines/Engine.cs b/src/BenchmarkDotNet/Engines/Engine.cs index 060f06a2c9..e436f7fdad 100644 --- a/src/BenchmarkDotNet/Engines/Engine.cs +++ b/src/BenchmarkDotNet/Engines/Engine.cs @@ -31,7 +31,7 @@ public class Engine : IEngine [PublicAPI] public IResolver Resolver { get; } [PublicAPI] public Encoding Encoding { get; } [PublicAPI] public string BenchmarkName { get; } - + private IClock Clock { get; } private bool ForceAllocations { get; } private int UnrollFactor { get; } @@ -51,7 +51,7 @@ internal Engine( Action globalSetupAction, Action globalCleanupAction, Action iterationSetupAction, Action iterationCleanupAction, long operationsPerInvoke, bool includeExtraStats, Encoding encoding, string benchmarkName) { - + Host = host; OverheadAction = overheadAction; Dummy1Action = dummy1Action; @@ -102,7 +102,7 @@ public RunResults Run() { long invokeCount = InvocationCount; IReadOnlyList idle = null; - + if (EngineEventSource.Log.IsEnabled()) EngineEventSource.Log.BenchmarkStart(BenchmarkName); @@ -128,10 +128,10 @@ public RunResults Run() Host.AfterMainRun(); - (GcStats workGcHasDone, ThreadingStats threadingStats) = includeExtraStats + (GcStats workGcHasDone, ThreadingStats threadingStats) = includeExtraStats ? GetExtraStats(new IterationData(IterationMode.Workload, IterationStage.Actual, 0, invokeCount, UnrollFactor)) : (GcStats.Empty, ThreadingStats.Empty); - + if (EngineEventSource.Log.IsEnabled()) EngineEventSource.Log.BenchmarkStop(BenchmarkName); @@ -194,7 +194,7 @@ public Measurement RunIteration(IterationData data) var finalGcStats = GcStats.ReadFinal(); var finalThreadingStats = ThreadingStats.ReadFinal(); - IterationCleanupAction(); // we run iteration cleanup after collecting GC stats + IterationCleanupAction(); // we run iteration cleanup after collecting GC stats GcStats gcStats = (finalGcStats - initialGcStats).WithTotalOperations(data.InvokeCount * OperationsPerInvoke); ThreadingStats threadingStats = (finalThreadingStats - initialThreadingStats).WithTotalOperations(data.InvokeCount * OperationsPerInvoke); @@ -244,12 +244,12 @@ private static readonly Dictionary SignalsToMessages { HostSignal.AfterAll, "// AfterAll" } }; - private static readonly Dictionary MessagesToSignals + private static readonly Dictionary MessagesToSignals = SignalsToMessages.ToDictionary(p => p.Value, p => p.Key); public static string ToMessage(HostSignal signal) => SignalsToMessages[signal]; - public static bool TryGetSignal(string message, out HostSignal signal) + public static bool TryGetSignal(string message, out HostSignal signal) => MessagesToSignals.TryGetValue(message, out signal); } } diff --git a/src/BenchmarkDotNet/Engines/EngineEventSource.cs b/src/BenchmarkDotNet/Engines/EngineEventSource.cs index dd6d9eceaf..d85695e708 100644 --- a/src/BenchmarkDotNet/Engines/EngineEventSource.cs +++ b/src/BenchmarkDotNet/Engines/EngineEventSource.cs @@ -26,7 +26,7 @@ public class EngineEventSource : EventSource public class Tasks { - [PublicAPI] public const EventTask Benchmark = (EventTask)1; + [PublicAPI] public const EventTask Benchmark = (EventTask)1; [PublicAPI] public const EventTask OverheadJitting = (EventTask)2; [PublicAPI] public const EventTask WorkloadJitting = (EventTask)3; [PublicAPI] public const EventTask WorkloadPilot = (EventTask)4; @@ -37,61 +37,61 @@ public class Tasks } internal static readonly EngineEventSource Log = new EngineEventSource(); - + private EngineEventSource() { } [Event(BenchmarkStartEventId, Level = EventLevel.Informational, Task = Tasks.Benchmark, Opcode = EventOpcode.Start)] internal void BenchmarkStart(string benchmarkName) => WriteEvent(BenchmarkStartEventId, benchmarkName); - + [Event(BenchmarkStopEventId, Level = EventLevel.Informational, Task = Tasks.Benchmark, Opcode = EventOpcode.Stop)] internal void BenchmarkStop(string benchmarkName) => WriteEvent(BenchmarkStopEventId, benchmarkName); - + [Event(OverheadJittingStartEventId, Level = EventLevel.Informational, Task = Tasks.OverheadJitting, Opcode = EventOpcode.Start)] internal void OverheadJittingStart(long totalOperations) => WriteEvent(OverheadJittingStartEventId, totalOperations); - + [Event(OverheadJittingStopEventId, Level = EventLevel.Informational, Task = Tasks.OverheadJitting, Opcode = EventOpcode.Stop)] internal void OverheadJittingStop(long totalOperations) => WriteEvent(OverheadJittingStopEventId, totalOperations); - + [Event(WorkloadJittingStartEventId, Level = EventLevel.Informational, Task = Tasks.WorkloadJitting, Opcode = EventOpcode.Start)] internal void WorkloadJittingStart(long totalOperations) => WriteEvent(WorkloadJittingStartEventId, totalOperations); - + [Event(WorkloadJittingStopEventId, Level = EventLevel.Informational, Task = Tasks.WorkloadJitting, Opcode = EventOpcode.Stop)] internal void WorkloadJittingStop(long totalOperations) => WriteEvent(WorkloadJittingStopEventId, totalOperations); - + [Event(WorkloadPilotStartEventId, Level = EventLevel.Informational, Task = Tasks.WorkloadPilot, Opcode = EventOpcode.Start)] internal void WorkloadPilotStart(long totalOperations) => WriteEvent(WorkloadPilotStartEventId, totalOperations); - + [Event(WorkloadPilotStopEventId, Level = EventLevel.Informational, Task = Tasks.WorkloadPilot, Opcode = EventOpcode.Stop)] internal void WorkloadPilotStop(long totalOperations) => WriteEvent(WorkloadPilotStopEventId, totalOperations); - + [Event(OverheadWarmupStartEventId, Level = EventLevel.Informational, Task = Tasks.OverheadWarmup, Opcode = EventOpcode.Start)] internal void OverheadWarmupStart(long totalOperations) => WriteEvent(OverheadWarmupStartEventId, totalOperations); - + [Event(OverheadWarmupStopEventId, Level = EventLevel.Informational, Task = Tasks.OverheadWarmup, Opcode = EventOpcode.Stop)] internal void OverheadWarmupStop(long totalOperations) => WriteEvent(OverheadWarmupStopEventId, totalOperations); - + [Event(OverheadActualStartEventId, Level = EventLevel.Informational, Task = Tasks.OverheadActual, Opcode = EventOpcode.Start)] internal void OverheadActualStart(long totalOperations) => WriteEvent(OverheadActualStartEventId, totalOperations); - + [Event(OverheadActualStopEventId, Level = EventLevel.Informational, Task = Tasks.OverheadActual, Opcode = EventOpcode.Stop)] internal void OverheadActualStop(long totalOperations) => WriteEvent(OverheadActualStopEventId, totalOperations); - + [Event(WorkloadWarmupStartEventId, Level = EventLevel.Informational, Task = Tasks.WorkloadWarmup, Opcode = EventOpcode.Start)] internal void WorkloadWarmupStart(long totalOperations) => WriteEvent(WorkloadWarmupStartEventId, totalOperations); - + [Event(WorkloadWarmupStopEventId, Level = EventLevel.Informational, Task = Tasks.WorkloadWarmup, Opcode = EventOpcode.Stop)] internal void WorkloadWarmupStop(long totalOperations) => WriteEvent(WorkloadWarmupStopEventId, totalOperations); - + [Event(WorkloadActualStartEventId, Level = EventLevel.Informational, Task = Tasks.WorkloadActual, Opcode = EventOpcode.Start)] internal void WorkloadActualStart(long totalOperations) => WriteEvent(WorkloadActualStartEventId, totalOperations); - + [Event(WorkloadActualStopEventId, Level = EventLevel.Informational, Task = Tasks.WorkloadActual, Opcode = EventOpcode.Stop)] internal void WorkloadActualStop(long totalOperations) => WriteEvent(WorkloadActualStopEventId, totalOperations); [NonEvent] internal void IterationStart(IterationMode mode, IterationStage stage, long totalOperations) { - switch (stage) + switch (stage) { case IterationStage.Jitting when mode == IterationMode.Overhead: OverheadJittingStart(totalOperations); @@ -118,11 +118,11 @@ internal void IterationStart(IterationMode mode, IterationStage stage, long tota throw new ArgumentOutOfRangeException(nameof(stage), stage, null); } } - + [NonEvent] internal void IterationStop(IterationMode mode, IterationStage stage, long totalOperations) { - switch (stage) + switch (stage) { case IterationStage.Jitting when mode == IterationMode.Overhead: OverheadJittingStop(totalOperations); diff --git a/src/BenchmarkDotNet/Engines/EngineFactory.cs b/src/BenchmarkDotNet/Engines/EngineFactory.cs index 1c9119b4e7..a7213983cf 100644 --- a/src/BenchmarkDotNet/Engines/EngineFactory.cs +++ b/src/BenchmarkDotNet/Engines/EngineFactory.cs @@ -26,24 +26,24 @@ public IEngine CreateReadyToRun(EngineParameters engineParameters) throw new ArgumentNullException(nameof(engineParameters.TargetJob)); engineParameters.GlobalSetupAction?.Invoke(); // whatever the settings are, we MUST call global setup here, the global cleanup is part of Engine's Dispose - + if (!engineParameters.NeedsJitting) // just create the engine, do NOT jit return CreateMultiActionEngine(engineParameters); int jitIndex = 0; - + if (engineParameters.HasInvocationCount || engineParameters.HasUnrollFactor) // it's a job with explicit configuration, just create the engine and jit it { var warmedUpMultiActionEngine = CreateMultiActionEngine(engineParameters); - + DeadCodeEliminationHelper.KeepAliveWithoutBoxing(Jit(warmedUpMultiActionEngine, ++jitIndex, invokeCount: engineParameters.UnrollFactor, unrollFactor: engineParameters.UnrollFactor)); return warmedUpMultiActionEngine; } - + var singleActionEngine = CreateSingleActionEngine(engineParameters); var singleInvocationTime = Jit(singleActionEngine, ++jitIndex, invokeCount: 1, unrollFactor: 1); - + if (singleInvocationTime > engineParameters.IterationTime) return singleActionEngine; // executing once takes longer than iteration time => long running benchmark, needs no pilot and no overhead @@ -55,17 +55,17 @@ public IEngine CreateReadyToRun(EngineParameters engineParameters) return singleActionEngine; int roundedUpTimesPerIteration = (int)Math.Ceiling(timesPerIteration); - + if (roundedUpTimesPerIteration < defaultUnrollFactor) // if we run it defaultUnrollFactor times per iteration, it's going to take longer than IterationTime { var needsPilot = engineParameters.TargetJob .WithUnrollFactor(1) // we don't want to use unroll factor! .WithMinInvokeCount(2) // the minimum is 2 (not the default 4 which can be too much and not 1 which we already know is not enough) .WithEvaluateOverhead(false); // it's something very time consuming, it overhead is too small compared to total time - + return CreateEngine(engineParameters, needsPilot, engineParameters.OverheadActionNoUnroll, engineParameters.WorkloadActionNoUnroll); } - + var multiActionEngine = CreateMultiActionEngine(engineParameters); DeadCodeEliminationHelper.KeepAliveWithoutBoxing(Jit(multiActionEngine, ++jitIndex, invokeCount: defaultUnrollFactor, unrollFactor: defaultUnrollFactor)); @@ -79,7 +79,7 @@ private static TimeInterval Jit(Engine engine, int jitIndex, int invokeCount, in engine.Dummy1Action.Invoke(); DeadCodeEliminationHelper.KeepAliveWithoutBoxing(engine.RunIteration(new IterationData(IterationMode.Overhead, IterationStage.Jitting, jitIndex, invokeCount, unrollFactor))); // don't forget to JIT idle - + engine.Dummy2Action.Invoke(); var result = engine.RunIteration(new IterationData(IterationMode.Workload, IterationStage.Jitting, jitIndex, invokeCount, unrollFactor)); @@ -87,20 +87,20 @@ private static TimeInterval Jit(Engine engine, int jitIndex, int invokeCount, in engine.Dummy3Action.Invoke(); engine.WriteLine(); - + return TimeInterval.FromNanoseconds(result.Nanoseconds); } - private static Engine CreateMultiActionEngine(EngineParameters engineParameters) + private static Engine CreateMultiActionEngine(EngineParameters engineParameters) => CreateEngine(engineParameters, engineParameters.TargetJob, engineParameters.OverheadActionUnroll, engineParameters.WorkloadActionUnroll); - private static Engine CreateSingleActionEngine(EngineParameters engineParameters) + private static Engine CreateSingleActionEngine(EngineParameters engineParameters) => CreateEngine(engineParameters, engineParameters.TargetJob - .WithInvocationCount(1).WithUnrollFactor(1) // run the benchmark exactly once per iteration + .WithInvocationCount(1).WithUnrollFactor(1) // run the benchmark exactly once per iteration .WithEvaluateOverhead(false), // it's something very time consuming, it overhead is too small compared to total time // todo: consider if we should set the warmup count to 2 - engineParameters.OverheadActionNoUnroll, + engineParameters.OverheadActionNoUnroll, engineParameters.WorkloadActionNoUnroll); private static Engine CreateEngine(EngineParameters engineParameters, Job job, Action idle, Action main) diff --git a/src/BenchmarkDotNet/Engines/EngineGeneralStage.cs b/src/BenchmarkDotNet/Engines/EngineGeneralStage.cs index 15cd3bddd4..647d82fa30 100644 --- a/src/BenchmarkDotNet/Engines/EngineGeneralStage.cs +++ b/src/BenchmarkDotNet/Engines/EngineGeneralStage.cs @@ -30,10 +30,10 @@ public EngineActualStage(IEngine engine) : base(engine) maxIterationCount = engine.TargetJob.ResolveValue(RunMode.MaxIterationCountCharacteristic, engine.Resolver); } - public IReadOnlyList RunOverhead(long invokeCount, int unrollFactor) + public IReadOnlyList RunOverhead(long invokeCount, int unrollFactor) => RunAuto(invokeCount, IterationMode.Overhead, unrollFactor); - public IReadOnlyList RunWorkload(long invokeCount, int unrollFactor, bool forceSpecific = false) + public IReadOnlyList RunWorkload(long invokeCount, int unrollFactor, bool forceSpecific = false) => Run(invokeCount, IterationMode.Workload, false, unrollFactor, forceSpecific); internal IReadOnlyList Run(long invokeCount, IterationMode iterationMode, bool runAuto, int unrollFactor, bool forceSpecific = false) diff --git a/src/BenchmarkDotNet/Engines/EngineParameters.cs b/src/BenchmarkDotNet/Engines/EngineParameters.cs index ecd3a913cf..2aa88a9e7b 100644 --- a/src/BenchmarkDotNet/Engines/EngineParameters.cs +++ b/src/BenchmarkDotNet/Engines/EngineParameters.cs @@ -11,7 +11,7 @@ namespace BenchmarkDotNet.Engines public class EngineParameters { public static readonly IResolver DefaultResolver = new CompositeResolver(BenchmarkRunnerClean.DefaultResolver, EngineResolver.Instance); - + public IHost Host { get; set; } public Action WorkloadActionNoUnroll { get; set; } public Action WorkloadActionUnroll { get; set; } @@ -27,19 +27,19 @@ public class EngineParameters public Action IterationSetupAction { get; set; } public Action IterationCleanupAction { get; set; } public bool MeasureExtraStats { get; set; } - + [PublicAPI] public Encoding Encoding { get; set; } - + [PublicAPI] public string BenchmarkName { get; set; } - + public bool NeedsJitting => TargetJob.ResolveValue(RunMode.RunStrategyCharacteristic, DefaultResolver).NeedsJitting(); public bool HasInvocationCount => TargetJob.HasValue(RunMode.InvocationCountCharacteristic); - + public bool HasUnrollFactor => TargetJob.HasValue(RunMode.UnrollFactorCharacteristic); public int UnrollFactor => TargetJob.ResolveValue(RunMode.UnrollFactorCharacteristic, DefaultResolver); - + public TimeInterval IterationTime => TargetJob.ResolveValue(RunMode.IterationTimeCharacteristic, DefaultResolver); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Engines/EngineResolver.cs b/src/BenchmarkDotNet/Engines/EngineResolver.cs index 35f6cd4ba9..eddbd31dc9 100644 --- a/src/BenchmarkDotNet/Engines/EngineResolver.cs +++ b/src/BenchmarkDotNet/Engines/EngineResolver.cs @@ -14,7 +14,7 @@ public class EngineResolver : Resolver internal const int ForceAutoWarmup = -1; internal const int DefaultMinWarmupIterationCount = 6; internal const int DefaultMaxWarmupIterationCount = 50; - + public static readonly IResolver Instance = new EngineResolver(); private EngineResolver() diff --git a/src/BenchmarkDotNet/Engines/EngineStage.cs b/src/BenchmarkDotNet/Engines/EngineStage.cs index 65ab7f4312..67c46267fc 100644 --- a/src/BenchmarkDotNet/Engines/EngineStage.cs +++ b/src/BenchmarkDotNet/Engines/EngineStage.cs @@ -19,7 +19,7 @@ protected Measurement RunIteration(IterationMode mode, IterationStage stage, int throw new ArgumentOutOfRangeException($"InvokeCount({invokeCount}) should be a multiple of UnrollFactor({unrollFactor})."); return engine.RunIteration(new IterationData(mode, stage, index, invokeCount, unrollFactor)); } - + internal List Run(IStoppingCriteria criteria, long invokeCount, IterationMode mode, IterationStage stage, int unrollFactor) { var measurements = new List(criteria.MaxIterationCount); diff --git a/src/BenchmarkDotNet/Engines/GcStats.cs b/src/BenchmarkDotNet/Engines/GcStats.cs index 96730c42f9..245604fcad 100644 --- a/src/BenchmarkDotNet/Engines/GcStats.cs +++ b/src/BenchmarkDotNet/Engines/GcStats.cs @@ -106,7 +106,7 @@ public long GetTotalAllocatedBytes(bool excludeAllocationQuantumSideEffects) public static GcStats ReadInitial() { // this will force GC.Collect, so we want to do this before collecting collections counts - long allocatedBytes = GetAllocatedBytes(); + long allocatedBytes = GetAllocatedBytes(); return new GcStats( GC.CollectionCount(0), @@ -123,9 +123,9 @@ public static GcStats ReadFinal() GC.CollectionCount(1), GC.CollectionCount(2), - // this will force GC.Collect, so we want to do this after collecting collections counts + // this will force GC.Collect, so we want to do this after collecting collections counts // to exclude this single full forced collection from results - GetAllocatedBytes(), + GetAllocatedBytes(), 0); } @@ -138,7 +138,7 @@ private static long GetAllocatedBytes() if (RuntimeInformation.IsMono) // Monitoring is not available in Mono, see http://stackoverflow.com/questions/40234948/how-to-get-the-number-of-allocated-bytes- return 0; - // "This instance Int64 property returns the number of bytes that have been allocated by a specific + // "This instance Int64 property returns the number of bytes that have been allocated by a specific // AppDomain. The number is accurate as of the last garbage collection." - CLR via C# // so we enforce GC.Collect here just to make sure we get accurate results GC.Collect(); @@ -171,7 +171,7 @@ private static Func CreateGetTotalAllocatedBytesDelegate() return method != null ? (Func)method.CreateDelegate(typeof(Func)) : null; } - public string ToOutputLine() + public string ToOutputLine() => $"{ResultsLinePrefix} {Gen0Collections} {Gen1Collections} {Gen2Collections} {AllocatedBytes} {TotalOperations}"; public static GcStats Parse(string line) diff --git a/src/BenchmarkDotNet/Engines/HostExtensions.cs b/src/BenchmarkDotNet/Engines/HostExtensions.cs index 28c19f80a4..41272610a4 100644 --- a/src/BenchmarkDotNet/Engines/HostExtensions.cs +++ b/src/BenchmarkDotNet/Engines/HostExtensions.cs @@ -5,7 +5,7 @@ namespace BenchmarkDotNet.Engines public static class HostExtensions { [StringFormatMethod("messageFormat")] - public static void WriteLine(this IHost host, string messageFormat, params object[] args) + public static void WriteLine(this IHost host, string messageFormat, params object[] args) => host.WriteLine(string.Format(messageFormat, args)); public static void BeforeAnythingElse(this IHost host) => host.SendSignal(HostSignal.BeforeAnythingElse); diff --git a/src/BenchmarkDotNet/Engines/HostSignal.cs b/src/BenchmarkDotNet/Engines/HostSignal.cs index e24939ce9c..f4a2f75a22 100644 --- a/src/BenchmarkDotNet/Engines/HostSignal.cs +++ b/src/BenchmarkDotNet/Engines/HostSignal.cs @@ -6,7 +6,7 @@ public enum HostSignal /// before we start the benchmarking process /// BeforeProcessStart, - + /// /// before jitting, warmup /// @@ -31,7 +31,7 @@ public enum HostSignal /// used to run some code independent to the benchmarked process /// SeparateLogic, - + /// /// after the benchmarking process exits /// diff --git a/src/BenchmarkDotNet/Engines/IterationMode.cs b/src/BenchmarkDotNet/Engines/IterationMode.cs index 1ca4e276d2..a65b7faeb0 100644 --- a/src/BenchmarkDotNet/Engines/IterationMode.cs +++ b/src/BenchmarkDotNet/Engines/IterationMode.cs @@ -3,9 +3,9 @@ public enum IterationMode { Overhead, - + Workload, - + Unknown } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Engines/IterationStage.cs b/src/BenchmarkDotNet/Engines/IterationStage.cs index 091be7f2b9..10a51a8aef 100644 --- a/src/BenchmarkDotNet/Engines/IterationStage.cs +++ b/src/BenchmarkDotNet/Engines/IterationStage.cs @@ -3,18 +3,18 @@ public enum IterationStage { Jitting, - + /// /// /// Pilot, - + Warmup, - + Actual, - + Result, - + Unknown } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Engines/RunResults.cs b/src/BenchmarkDotNet/Engines/RunResults.cs index 351a355023..741dd01654 100644 --- a/src/BenchmarkDotNet/Engines/RunResults.cs +++ b/src/BenchmarkDotNet/Engines/RunResults.cs @@ -13,7 +13,7 @@ public struct RunResults { private readonly OutlierMode outlierMode; private readonly Encoding encoding; - + [CanBeNull, PublicAPI] public IReadOnlyList Overhead { get; } @@ -55,7 +55,7 @@ public IEnumerable GetMeasurements() yield return new Measurement( measurement.LaunchIndex, IterationMode.Workload, - IterationStage.Result, + IterationStage.Result, ++resultIndex, measurement.Operations, value, diff --git a/src/BenchmarkDotNet/Engines/StoppingCriteria/IStoppingCriteria.cs b/src/BenchmarkDotNet/Engines/StoppingCriteria/IStoppingCriteria.cs index 322c6c0cf1..6030739ebe 100644 --- a/src/BenchmarkDotNet/Engines/StoppingCriteria/IStoppingCriteria.cs +++ b/src/BenchmarkDotNet/Engines/StoppingCriteria/IStoppingCriteria.cs @@ -19,14 +19,14 @@ public interface IStoppingCriteria /// [NotNull] string Title { get; } - + /// /// The maximum possible count of iterations. /// Engine needs this value for setting the maximum capacity of the returned list of measurements. /// The correct capacity helps to avoid infrastructure allocations during benchmarking. /// int MaxIterationCount { get; } - + /// /// An array of user-friendly warnings which notify about incorrect parameters. /// diff --git a/src/BenchmarkDotNet/Engines/ThreadingStats.cs b/src/BenchmarkDotNet/Engines/ThreadingStats.cs index 98816bc340..fbb35fd94b 100644 --- a/src/BenchmarkDotNet/Engines/ThreadingStats.cs +++ b/src/BenchmarkDotNet/Engines/ThreadingStats.cs @@ -58,7 +58,7 @@ public static ThreadingStats Parse(string line) return new ThreadingStats(completedWorkItemCount, lockContentionCount, totalOperationsCount); } - public static ThreadingStats operator +(ThreadingStats left, ThreadingStats right) + public static ThreadingStats operator +(ThreadingStats left, ThreadingStats right) => new ThreadingStats( left.CompletedWorkItemCount + right.CompletedWorkItemCount, left.LockContentionCount + right.LockContentionCount, diff --git a/src/BenchmarkDotNet/Environments/EnvironmentResolver.cs b/src/BenchmarkDotNet/Environments/EnvironmentResolver.cs index e0497e9e8f..74bbc6c672 100644 --- a/src/BenchmarkDotNet/Environments/EnvironmentResolver.cs +++ b/src/BenchmarkDotNet/Environments/EnvironmentResolver.cs @@ -39,7 +39,7 @@ private EnvironmentResolver() throw new NotSupportedException($"Unknown runStrategy: {strategy}"); } }); - Register(RunMode.InvocationCountCharacteristic, () => 1); + Register(RunMode.InvocationCountCharacteristic, () => 1); } } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Environments/HostEnvironmentInfo.cs b/src/BenchmarkDotNet/Environments/HostEnvironmentInfo.cs index f9ec4196ab..cb2850a164 100644 --- a/src/BenchmarkDotNet/Environments/HostEnvironmentInfo.cs +++ b/src/BenchmarkDotNet/Environments/HostEnvironmentInfo.cs @@ -14,7 +14,7 @@ namespace BenchmarkDotNet.Environments { - // this class is used by our auto-generated benchmark program, + // this class is used by our auto-generated benchmark program, // keep it in mind if you want to do some renaming // you can find the source code at Templates\BenchmarkProgram.txt public class HostEnvironmentInfo : BenchmarkEnvironmentInfo @@ -110,7 +110,7 @@ public override IEnumerable ToFormattedString() private static string GetBenchmarkDotNetVersion() => BenchmarkDotNetInfo.FullVersion; /// - /// Return string representation of CPU and environment configuration including BenchmarkDotNet, OS and .NET version + /// Return string representation of CPU and environment configuration including BenchmarkDotNet, OS and .NET version /// [PublicAPI] public static string GetInformation() diff --git a/src/BenchmarkDotNet/Environments/Jit.cs b/src/BenchmarkDotNet/Environments/Jit.cs index 63d42279bb..976cc4f773 100644 --- a/src/BenchmarkDotNet/Environments/Jit.cs +++ b/src/BenchmarkDotNet/Environments/Jit.cs @@ -7,7 +7,7 @@ public enum Jit /// By default /// Default, - + /// /// LegacyJIT /// Supported only for Full Framework diff --git a/src/BenchmarkDotNet/Environments/OsBrandStringHelper.cs b/src/BenchmarkDotNet/Environments/OsBrandStringHelper.cs index 7899115819..d52d067f73 100644 --- a/src/BenchmarkDotNet/Environments/OsBrandStringHelper.cs +++ b/src/BenchmarkDotNet/Environments/OsBrandStringHelper.cs @@ -231,7 +231,7 @@ public static string PrettifyMacOSX([NotNull] string systemVersion, [NotNull] st string systemVersionNumbers = systemVersion.Substring(firstDigitIndex).Trim(); return $"{systemVersionTitle} {codeName} {systemVersionNumbers} [{kernelVersion}]"; } - + return $"{systemVersion} [{kernelVersion}]"; } } diff --git a/src/BenchmarkDotNet/Environments/Platform.cs b/src/BenchmarkDotNet/Environments/Platform.cs index 30a156b540..5e92999d81 100644 --- a/src/BenchmarkDotNet/Environments/Platform.cs +++ b/src/BenchmarkDotNet/Environments/Platform.cs @@ -16,12 +16,12 @@ public enum Platform /// x64 /// X64, - + /// /// ARM /// Arm, - + /// /// ARM64 /// diff --git a/src/BenchmarkDotNet/Environments/ProcessorBrandStringHelper.cs b/src/BenchmarkDotNet/Environments/ProcessorBrandStringHelper.cs index f9741391e4..43376f3687 100644 --- a/src/BenchmarkDotNet/Environments/ProcessorBrandStringHelper.cs +++ b/src/BenchmarkDotNet/Environments/ProcessorBrandStringHelper.cs @@ -29,7 +29,7 @@ public static string Prettify(CpuInfo cpuInfo, bool includeMaxFrequency = false) // Remove parts which don't provide any useful information for user var processorName = cpuInfo.ProcessorName.Replace("@", "").Replace("(R)", "").Replace("(TM)", ""); - + // If we have found physical core(s), we can safely assume we can drop extra info from brand if (cpuInfo.PhysicalCoreCount.HasValue && cpuInfo.PhysicalCoreCount.Value > 0) processorName = Regex.Replace(processorName, @"(\w+?-Core Processor)", "").Trim(); @@ -41,7 +41,7 @@ public static string Prettify(CpuInfo cpuInfo, bool includeMaxFrequency = false) string maxFrequency = processorName.Contains("Hz") ? $"(Max: {frequencyString})" : frequencyString; processorName = $"{processorName} {maxFrequency}"; } - + // Remove double spaces processorName = Regex.Replace(processorName.Trim(), @"\s+", " "); @@ -127,7 +127,7 @@ internal static string ParseIntelCoreMicroarchitecture([NotNull] string modelNum { if (KnownMicroarchitectures.Value.ContainsKey(modelNumber)) return KnownMicroarchitectures.Value[modelNumber]; - + if (modelNumber.Length >= 3 && modelNumber.Substring(0, 3).All(char.IsDigit) && (modelNumber.Length == 3 || !char.IsDigit(modelNumber[3]))) return "Nehalem"; diff --git a/src/BenchmarkDotNet/Environments/Runtimes/ClrRuntime.cs b/src/BenchmarkDotNet/Environments/Runtimes/ClrRuntime.cs index f65c3d01c6..a72c5580db 100644 --- a/src/BenchmarkDotNet/Environments/Runtimes/ClrRuntime.cs +++ b/src/BenchmarkDotNet/Environments/Runtimes/ClrRuntime.cs @@ -52,7 +52,7 @@ internal static ClrRuntime GetCurrentVersion() string sdkVersion = FrameworkVersionHelper.GetLatestNetDeveloperPackVersion(); string version = sdkVersion - ?? FrameworkVersionHelper.GetFrameworkReleaseVersion(); // .NET Developer Pack is not installed + ?? FrameworkVersionHelper.GetFrameworkReleaseVersion(); // .NET Developer Pack is not installed switch (version) { diff --git a/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs b/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs index 2ea5b4c8ae..8d6bb91a29 100644 --- a/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs +++ b/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs @@ -93,7 +93,7 @@ internal static bool TryGetVersion(out Version version) if (RuntimeInformation.IsRunningInContainer) { - return Version.TryParse(Environment.GetEnvironmentVariable("DOTNET_VERSION"), out version) + return Version.TryParse(Environment.GetEnvironmentVariable("DOTNET_VERSION"), out version) || Version.TryParse(Environment.GetEnvironmentVariable("ASPNETCORE_VERSION"), out version); } @@ -115,7 +115,7 @@ internal static bool TryGetVersionFromRuntimeDirectory(string runtimeDirectory, return false; } - // sample input: + // sample input: // 2.0: 4.6.26614.01 @BuiltBy: dlab14-DDVSOWINAGE018 @Commit: a536e7eec55c538c94639cefe295aa672996bf9b, Microsoft .NET Framework // 2.1: 4.6.27817.01 @BuiltBy: dlab14-DDVSOWINAGE101 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/coreclr/tree/6f78fbb3f964b4f407a2efb713a186384a167e5c, Microsoft .NET Framework // 2.2: 4.6.27817.03 @BuiltBy: dlab14-DDVSOWINAGE101 @Branch: release/2.2 @SrcCode: https://github.com/dotnet/coreclr/tree/ce1d090d33b400a25620c0145046471495067cc7, Microsoft .NET Framework diff --git a/src/BenchmarkDotNet/Environments/Runtimes/MonoRuntime.cs b/src/BenchmarkDotNet/Environments/Runtimes/MonoRuntime.cs index 908d8e7afc..9f6049a197 100644 --- a/src/BenchmarkDotNet/Environments/Runtimes/MonoRuntime.cs +++ b/src/BenchmarkDotNet/Environments/Runtimes/MonoRuntime.cs @@ -28,10 +28,10 @@ public MonoRuntime(string name, string customPath, string aotArgs, string monoBc public override bool Equals(object obj) => obj is MonoRuntime other && Equals(other); - public bool Equals(MonoRuntime other) + public bool Equals(MonoRuntime other) => base.Equals(other) && Name == other?.Name && CustomPath == other?.CustomPath && AotArgs == other?.AotArgs && MonoBclPath == other?.MonoBclPath; - public override int GetHashCode() + public override int GetHashCode() => base.GetHashCode() ^ Name.GetHashCode() ^ (CustomPath?.GetHashCode() ?? 0) ^ (AotArgs?.GetHashCode() ?? 0) ^ (MonoBclPath?.GetHashCode() ?? 0); } } diff --git a/src/BenchmarkDotNet/Environments/Runtimes/Runtime.cs b/src/BenchmarkDotNet/Environments/Runtimes/Runtime.cs index 657d3650c5..e61778fd69 100644 --- a/src/BenchmarkDotNet/Environments/Runtimes/Runtime.cs +++ b/src/BenchmarkDotNet/Environments/Runtimes/Runtime.cs @@ -26,7 +26,7 @@ public abstract class Runtime : IEquatable /// /// Display name /// - [PublicAPI] + [PublicAPI] public string Name { get; } /// diff --git a/src/BenchmarkDotNet/Exporters/BenchmarkReportExporter.cs b/src/BenchmarkDotNet/Exporters/BenchmarkReportExporter.cs index ba86504ef6..fe966bbbd6 100644 --- a/src/BenchmarkDotNet/Exporters/BenchmarkReportExporter.cs +++ b/src/BenchmarkDotNet/Exporters/BenchmarkReportExporter.cs @@ -11,7 +11,7 @@ public class BenchmarkReportExporter: ExporterBase private BenchmarkReportExporter() { } - + public override void ExportToLog(Summary summary, ILogger logger) { foreach (var report in summary.Reports) diff --git a/src/BenchmarkDotNet/Exporters/CombinedDisassemblyExporter.cs b/src/BenchmarkDotNet/Exporters/CombinedDisassemblyExporter.cs index 2163e6ffc5..610f5694bb 100644 --- a/src/BenchmarkDotNet/Exporters/CombinedDisassemblyExporter.cs +++ b/src/BenchmarkDotNet/Exporters/CombinedDisassemblyExporter.cs @@ -42,18 +42,18 @@ public override void ExportToLog(Summary summary, ILogger logger) foreach (var targetingSameMethod in benchmarksByTarget) { PrintTable( - targetingSameMethod.ToArray(), - logger, - targetingSameMethod.First().Descriptor.DisplayInfo, + targetingSameMethod.ToArray(), + logger, + targetingSameMethod.First().Descriptor.DisplayInfo, benchmark => GetImportantInfo(summary[benchmark])); } } else // different methods, same JIT { PrintTable( - summary.BenchmarksCases.Where(benchmark => results.ContainsKey(benchmark)).ToArray(), - logger, - summary.Title, + summary.BenchmarksCases.Where(benchmark => results.ContainsKey(benchmark)).ToArray(), + logger, + summary.Title, benchmark => $"{benchmark.Descriptor.WorkloadMethod.Name} {GetImportantInfo(summary[benchmark])}"); } @@ -73,7 +73,7 @@ private void PrintTable(BenchmarkCase[] benchmarksCase, ILogger logger, string t } logger.WriteLine(""); logger.WriteLine(""); - + logger.WriteLine(""); logger.WriteLine(""); foreach (var benchmark in benchmarksCase) diff --git a/src/BenchmarkDotNet/Exporters/CompositeExporter.cs b/src/BenchmarkDotNet/Exporters/CompositeExporter.cs index c9436eb0b9..360c26851c 100644 --- a/src/BenchmarkDotNet/Exporters/CompositeExporter.cs +++ b/src/BenchmarkDotNet/Exporters/CompositeExporter.cs @@ -10,7 +10,7 @@ namespace BenchmarkDotNet.Exporters public class CompositeExporter : IExporter { private readonly ImmutableArray exporters; - + public CompositeExporter(ImmutableArray exporters) => this.exporters = exporters; public string Name => nameof(CompositeExporter); @@ -24,7 +24,7 @@ public void ExportToLog(Summary summary, ILogger logger) exporter.ExportToLog(summary, logger); } - public IEnumerable ExportToFiles(Summary summary, ILogger consoleLogger) + public IEnumerable ExportToFiles(Summary summary, ILogger consoleLogger) => exporters.SelectMany(exporter => exporter.ExportToFiles(summary, consoleLogger)); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs b/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs index c57d8c8518..543f2f4ac5 100644 --- a/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs +++ b/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs @@ -88,7 +88,7 @@ private static MeasurementColumn[] BuildColumns() new MeasurementColumn("Target_Type", (summary, report, m) => report.BenchmarkCase.Descriptor.Type.Name), new MeasurementColumn("Target_Method", (summary, report, m) => report.BenchmarkCase.Descriptor.WorkloadMethodDisplayInfo) }; - + // Job foreach (var characteristic in CharacteristicHelper.GetAllPresentableCharacteristics(typeof(Job), true)) columns.Add(new MeasurementColumn("Job_" + characteristic.Id, (summary, report, m) => Presenter.ToPresentation(report.BenchmarkCase.Job, characteristic))); diff --git a/src/BenchmarkDotNet/Exporters/FullNameProvider.cs b/src/BenchmarkDotNet/Exporters/FullNameProvider.cs index 8f77510748..4e6d3c1828 100644 --- a/src/BenchmarkDotNet/Exporters/FullNameProvider.cs +++ b/src/BenchmarkDotNet/Exporters/FullNameProvider.cs @@ -12,7 +12,7 @@ namespace BenchmarkDotNet.Exporters { - public static class FullNameProvider + public static class FullNameProvider { private static readonly IReadOnlyDictionary Aliases = new Dictionary { @@ -45,7 +45,7 @@ public static class FullNameProvider { typeof(bool?), "bool?" }, { typeof(char?), "char?" } }; - + [PublicAPI("used by the dotnet/performance repository")] public static string GetBenchmarkName(BenchmarkCase benchmarkCase) { @@ -116,14 +116,14 @@ private static string GetBenchmarkParameters(MethodInfo method, ParameterInstanc parametersBuilder.Append(methodArguments[i].Name).Append(':').Append(' '); parametersBuilder.Append(GetArgument(benchmarkParameters.GetArgument(methodArguments[i].Name).Value, methodArguments[i].ParameterType)); } - + for (int i = 0; i < benchmarkParams.Length; i++) { var parameter = benchmarkParams[i]; - + if (methodArguments.Length > 0 || i > 0) parametersBuilder.Append(", "); - + parametersBuilder.Append(parameter.Name).Append(':').Append(' '); parametersBuilder.Append(GetArgument(parameter.Value, parameter.Value?.GetType())); } @@ -194,7 +194,7 @@ private static string GetTypeArgumentName(Type type) if (type.IsNullable()) return $"{GetTypeArgumentName(Nullable.GetUnderlyingType(type))}?"; - + if (!string.IsNullOrEmpty(type.Namespace)) return $"{type.Namespace}.{GetTypeName(type)}"; diff --git a/src/BenchmarkDotNet/Exporters/Json/JsonExporterBase.cs b/src/BenchmarkDotNet/Exporters/Json/JsonExporterBase.cs index e08ff02044..640b45d855 100644 --- a/src/BenchmarkDotNet/Exporters/Json/JsonExporterBase.cs +++ b/src/BenchmarkDotNet/Exporters/Json/JsonExporterBase.cs @@ -68,7 +68,7 @@ public override void ExportToLog(Summary summary, ILogger logger) { data.Add("Memory", report.GcStats); } - + if (ExcludeMeasurements == false) { // We construct Measurements manually, so that we can have the IterationMode enum as text, rather than an integer diff --git a/src/BenchmarkDotNet/Exporters/PrettyHtmlDisassemblyExporter.cs b/src/BenchmarkDotNet/Exporters/PrettyHtmlDisassemblyExporter.cs index 8c473d2d7b..7dbfd28902 100644 --- a/src/BenchmarkDotNet/Exporters/PrettyHtmlDisassemblyExporter.cs +++ b/src/BenchmarkDotNet/Exporters/PrettyHtmlDisassemblyExporter.cs @@ -12,7 +12,7 @@ namespace BenchmarkDotNet.Exporters public class PrettyHtmlDisassemblyExporter : ExporterBase { private static readonly Lazy HighlightingLabelsScript = new Lazy(() => ResourceHelper.LoadTemplate("highlightingLabelsScript.js")); - + private readonly IReadOnlyDictionary results; public PrettyHtmlDisassemblyExporter(IReadOnlyDictionary results) => this.results = results; @@ -66,7 +66,7 @@ private static void Export(ILogger logger, Summary summary, DisassemblyResult di logger.WriteLine($""); logger.WriteLine($"
{label.TextRepresentation}
"); logger.WriteLine(" "); - + continue; } diff --git a/src/BenchmarkDotNet/Exporters/RawDisassemblyExporter.cs b/src/BenchmarkDotNet/Exporters/RawDisassemblyExporter.cs index dcba3c236b..8ba0c4a19a 100644 --- a/src/BenchmarkDotNet/Exporters/RawDisassemblyExporter.cs +++ b/src/BenchmarkDotNet/Exporters/RawDisassemblyExporter.cs @@ -51,7 +51,7 @@ private static void Export(ILogger logger, Summary summary, DisassemblyResult di $"{FormatMethodAddress(method.NativeCode)} {method.Name}"); // there is no need to distinguish the maps visually if there is only one type of code - bool diffTheMaps = method.Maps.SelectMany(map => map.Instructions).Select(ins => ins.GetType()).Distinct().Count() > 1; + bool diffTheMaps = method.Maps.SelectMany(map => map.Instructions).Select(ins => ins.GetType()).Distinct().Count() > 1; bool evenMap = true; foreach (var map in method.Maps) @@ -75,7 +75,7 @@ private static void Export(ILogger logger, Summary summary, DisassemblyResult di evenMap = !evenMap; } - + if(!string.IsNullOrEmpty(method.CommandLine)) logger.WriteLine($"{method.CommandLine}"); diff --git a/src/BenchmarkDotNet/Extensions/CommonExtensions.cs b/src/BenchmarkDotNet/Extensions/CommonExtensions.cs index bddafaf690..41c6bcea99 100644 --- a/src/BenchmarkDotNet/Extensions/CommonExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/CommonExtensions.cs @@ -54,7 +54,7 @@ public static string ToStr(this double value, string format = "0.##") // it will be resolved to: // string.Format(System.IFormatProvider, string, params object[]) // .NET 4.5 // string.Format(System.IFormatProvider, string, object) // .NET 4.6 - // Unfortunately, Mono doesn't have the second overload (with object instead of params object[]). + // Unfortunately, Mono doesn't have the second overload (with object instead of params object[]). var args = new object[] { value }; return string.Format(HostEnvironmentInfo.MainCultureInfo, $"{{0:{format}}}", args); } @@ -89,7 +89,7 @@ public static void AddRange(this HashSet hashSet, IEnumerable collectio foreach (var item in collection) hashSet.Add(item); } - + public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key) => dictionary.TryGetValue(key, out var value) ? value : default; diff --git a/src/BenchmarkDotNet/Extensions/EncodingExtensions.cs b/src/BenchmarkDotNet/Extensions/EncodingExtensions.cs index e094b834de..4c23f05fb6 100644 --- a/src/BenchmarkDotNet/Extensions/EncodingExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/EncodingExtensions.cs @@ -11,7 +11,7 @@ internal static string ToTemplateString(this Encoding encoding) { case UnicodeEncoding u: return result + u.EncodingName; - default: + default: return result + "ASCII"; } } diff --git a/src/BenchmarkDotNet/Extensions/ProcessExtensions.cs b/src/BenchmarkDotNet/Extensions/ProcessExtensions.cs index 16a32df2b7..3b49fbc075 100644 --- a/src/BenchmarkDotNet/Extensions/ProcessExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/ProcessExtensions.cs @@ -32,7 +32,7 @@ public static void EnsureHighPriority(this Process process, ILogger logger) logger.WriteLineError($"Failed to set up high priority. Make sure you have the right permissions. Message: {ex.Message}"); } } - + internal static string ToPresentation(this IntPtr processorAffinity, int processorCount) => (RuntimeInformation.Is64BitPlatform() ? Convert.ToString(processorAffinity.ToInt64(), 2) @@ -125,7 +125,7 @@ internal static void SetEnvironmentVariables(this ProcessStartInfo start, Benchm foreach (var environmentVariable in benchmarkCase.Job.Environment.EnvironmentVariables) start.EnvironmentVariables[environmentVariable.Key] = environmentVariable.Value; } - + // the code below was copy-pasted from https://github.com/dotnet/cli/blob/0bc24bff775e22352c2309ef990281280f92dbaa/test/Microsoft.DotNet.Tools.Tests.Utilities/Extensions/ProcessExtensions.cs#L13 public static void KillTree(this Process process) => process.KillTree(DefaultKillTimeout); diff --git a/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs b/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs index 0f19ad3830..880497b357 100644 --- a/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs @@ -60,7 +60,7 @@ internal static string GetCorrectCSharpTypeName(this Type type, bool includeName parent = parent.DeclaringType; } prefix += nestedTypes; - + if (type.GetTypeInfo().IsGenericParameter) return type.Name; @@ -140,9 +140,9 @@ internal static bool ContainsRunnableBenchmarks(this Type type) { var typeInfo = type.GetTypeInfo(); - if (typeInfo.IsAbstract - || typeInfo.IsSealed - || typeInfo.IsNotPublic + if (typeInfo.IsAbstract + || typeInfo.IsSealed + || typeInfo.IsNotPublic || typeInfo.IsGenericType && !IsRunnableGenericType(typeInfo)) return false; @@ -160,18 +160,18 @@ internal static (string Name, TAttribute Attribute, bool IsPrivate, bool IsStati { var allFields = type.GetFields(reflectionFlags) .Select(f => ( - Name: f.Name, + Name: f.Name, Attribute: f.ResolveAttribute(), IsPrivate: f.IsPrivate, - IsStatic: f.IsStatic, + IsStatic: f.IsStatic, ParameterType: f.FieldType)); var allProperties = type.GetProperties(reflectionFlags) .Select(p => ( - Name: p.Name, - Attribute: p.ResolveAttribute(), - IsPrivate: p.GetSetMethod() == null, - IsStatic: p.GetSetMethod() != null && p.GetSetMethod().IsStatic, + Name: p.Name, + Attribute: p.ResolveAttribute(), + IsPrivate: p.GetSetMethod() == null, + IsStatic: p.GetSetMethod() != null && p.GetSetMethod().IsStatic, PropertyType: p.PropertyType)); var joined = allFields.Concat(allProperties).Where(member => member.Attribute != null).ToArray(); @@ -186,7 +186,7 @@ internal static bool IsStackOnlyWithImplicitCast(this Type argumentType, object { if (argumentInstance == null) return false; - + // IsByRefLikeAttribute is not exposed for older runtimes, so we need to check it in an ugly way ;) bool isByRefLike = argumentType.GetCustomAttributes().Any(attribute => attribute.ToString().Contains("IsByRefLike")); if (!isByRefLike) @@ -197,7 +197,7 @@ internal static bool IsStackOnlyWithImplicitCast(this Type argumentType, object var implicitCastsDefinedInArgumentInstance = instanceType.GetMethods().Where(method => method.Name == "op_Implicit" && method.GetParameters().Any()).ToArray(); if (implicitCastsDefinedInArgumentInstance.Any(implicitCast => implicitCast.ReturnType == argumentType && implicitCast.GetParameters().All(p => p.ParameterType == instanceType))) return true; - + var implicitCastsDefinedInArgumentType = argumentType.GetMethods().Where(method => method.Name == "op_Implicit" && method.GetParameters().Any()).ToArray(); if (implicitCastsDefinedInArgumentType.Any(implicitCast => implicitCast.ReturnType == argumentType && implicitCast.GetParameters().All(p => p.ParameterType == instanceType))) return true; @@ -208,7 +208,7 @@ internal static bool IsStackOnlyWithImplicitCast(this Type argumentType, object private static bool IsRunnableGenericType(TypeInfo typeInfo) => // if it is an open generic - there must be GenericBenchmark attributes (!typeInfo.IsGenericTypeDefinition || typeInfo.GenericTypeArguments.Any() || typeInfo.GetCustomAttributes(true).OfType().Any()) - && typeInfo.DeclaredConstructors.Any(ctor => ctor.IsPublic && ctor.GetParameters().Length == 0); // we need public parameterless ctor to create it + && typeInfo.DeclaredConstructors.Any(ctor => ctor.IsPublic && ctor.GetParameters().Length == 0); // we need public parameterless ctor to create it internal static bool IsLinqPad(this Assembly assembly) => assembly.FullName.IndexOf("LINQPAD", StringComparison.OrdinalIgnoreCase) >= 0; } diff --git a/src/BenchmarkDotNet/Extensions/StringAndTextExtensions.cs b/src/BenchmarkDotNet/Extensions/StringAndTextExtensions.cs index 8f25182eb7..3e6e9da833 100644 --- a/src/BenchmarkDotNet/Extensions/StringAndTextExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/StringAndTextExtensions.cs @@ -34,9 +34,9 @@ internal static string AsValidFileName(this string inputPath) private static Dictionary BuildInvalidPathCharactersMappings() { var invalidFileNameChars = Path.GetInvalidFileNameChars().ToList(); - + // '\\' is a valid file name char on Unix - // which can be a problem when we are working with MSBuild + // which can be a problem when we are working with MSBuild if (!invalidFileNameChars.Contains('\\')) invalidFileNameChars.Add('\\'); @@ -84,7 +84,7 @@ internal static string HtmlEncode(this string s) } return sb.ToString(); } - + /// /// Returns file base name /// diff --git a/src/BenchmarkDotNet/Filters/GlobFilter.cs b/src/BenchmarkDotNet/Filters/GlobFilter.cs index d73a314c52..218591182d 100644 --- a/src/BenchmarkDotNet/Filters/GlobFilter.cs +++ b/src/BenchmarkDotNet/Filters/GlobFilter.cs @@ -13,7 +13,7 @@ public class GlobFilter : IFilter { private readonly (string userValue, Regex regex)[] patterns; - public GlobFilter(string[] patterns) + public GlobFilter(string[] patterns) => this.patterns = patterns.Select(pattern => (pattern, new Regex(WildcardToRegex(pattern), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))).ToArray(); public bool Predicate(BenchmarkCase benchmarkCase) diff --git a/src/BenchmarkDotNet/Helpers/CodeAnnotations.cs b/src/BenchmarkDotNet/Helpers/CodeAnnotations.cs index 1bbe20945d..0b538aa87d 100644 --- a/src/BenchmarkDotNet/Helpers/CodeAnnotations.cs +++ b/src/BenchmarkDotNet/Helpers/CodeAnnotations.cs @@ -39,7 +39,7 @@ namespace JetBrains.Annotations ///
/// /// [CanBeNull] object Test() => null; - /// + /// /// void UseTest() { /// var p = Test(); /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' @@ -101,7 +101,7 @@ internal sealed class ImplicitNotNullAttribute : Attribute { } /// /// [StringFormatMethod("message")] /// void ShowError(string message, params object[] args) { /* do something */ } - /// + /// /// void Foo() { /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string /// } @@ -171,12 +171,12 @@ internal sealed class InvokerParameterNameAttribute : Attribute { } /// /// public class Foo : INotifyPropertyChanged { /// public event PropertyChangedEventHandler PropertyChanged; - /// + /// /// [NotifyPropertyChangedInvocator] /// protected virtual void NotifyChanged(string propertyName) { ... } /// /// string _name; - /// + /// /// public string Name { /// get { return _name; } /// set { _name = value; NotifyChanged("LastName"); /* Warning */ } @@ -240,7 +240,7 @@ public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) /// // A method that returns null if the parameter is null, /// // and not null if the parameter is not null /// [ContractAnnotation("null => null; notnull => notnull")] - /// public object Transform(object data) + /// public object Transform(object data) /// /// /// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")] @@ -294,7 +294,7 @@ public LocalizationRequiredAttribute(bool required) /// /// [CannotApplyEqualityOperator] /// class NoEquality { } - /// + /// /// class UsesNoEquality { /// void Test() { /// var ca1 = new NoEquality(); @@ -315,7 +315,7 @@ internal sealed class CannotApplyEqualityOperatorAttribute : Attribute { } /// /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement /// class ComponentAttribute : Attribute { } - /// + /// /// [Component] // ComponentAttribute requires implementing IComponent interface /// class MyComponent : IComponent { } /// @@ -449,7 +449,7 @@ internal sealed class InstantHandleAttribute : Attribute { } /// /// /// [Pure] int Multiply(int x, int y) => x * y; - /// + /// /// void M() { /// Multiply(123, 42); // Waring: Return value of pure method is not used /// } @@ -481,7 +481,7 @@ public MustUseReturnValueAttribute([NotNull] string justification) /// /// class Foo { /// [ProvidesContext] IBarService _barService = ...; - /// + /// /// void ProcessNode(INode node) { /// DoSomething(node, node.GetGlobalServices().Bar); /// // ^ Warning: use value of '_barService' field @@ -748,7 +748,7 @@ internal sealed class AspMvcSuppressViewErrorAttribute : Attribute { } /// /// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template. - /// Use this attribute for custom wrappers similar to + /// Use this attribute for custom wrappers similar to /// System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String). /// [AttributeUsage(AttributeTargets.Parameter)] @@ -834,7 +834,7 @@ public HtmlAttributeValueAttribute([NotNull] string name) /// /// Razor attribute. Indicates that a parameter or a method is a Razor section. - /// Use this attribute for custom wrappers similar to + /// Use this attribute for custom wrappers similar to /// System.Web.WebPages.WebPageBase.RenderSection(String). /// [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] @@ -870,7 +870,7 @@ internal enum CollectionAccessType /// /// Indicates that the marked method is assertion method, i.e. it halts control flow if - /// one of the conditions is satisfied. To set the condition, mark one of the parameters with + /// one of the conditions is satisfied. To set the condition, mark one of the parameters with /// attribute. /// [AttributeUsage(AttributeTargets.Method)] diff --git a/src/BenchmarkDotNet/Helpers/DirtyAssemblyResolveHelper.cs b/src/BenchmarkDotNet/Helpers/DirtyAssemblyResolveHelper.cs index 6c31019051..a16e15f653 100644 --- a/src/BenchmarkDotNet/Helpers/DirtyAssemblyResolveHelper.cs +++ b/src/BenchmarkDotNet/Helpers/DirtyAssemblyResolveHelper.cs @@ -7,9 +7,9 @@ /// Sometimes NuGet/VS/other tool does not generate the right assembly binding redirects /// or just for any other magical reasons /// our users get FileNotFoundException when trying to run their benchmarks -/// +/// /// We want our users to be happy and we try to help the .NET framework when it fails to load an assembly -/// +/// /// It's not recommended to copy this code OR reuse it anywhere. It's an UGLY WORKAROUND. /// /// If one day we can remove it, the person doing that should celebrate!! @@ -40,7 +40,7 @@ private Assembly HelpTheFrameworkToResolveTheAssembly(object sender, ResolveEven // the file is right there, but has most probably different version and there is no assembly redirect // so we just load it and ignore the version mismatch - // we can at least try because benchmarks are not executed in the Host process, + // we can at least try because benchmarks are not executed in the Host process, // so even if we load some bad version of the assembly // we might still produce the right exe with proper references diff --git a/src/BenchmarkDotNet/Helpers/FolderNameHelper.cs b/src/BenchmarkDotNet/Helpers/FolderNameHelper.cs index 64879e5500..e2a57fba98 100644 --- a/src/BenchmarkDotNet/Helpers/FolderNameHelper.cs +++ b/src/BenchmarkDotNet/Helpers/FolderNameHelper.cs @@ -35,7 +35,7 @@ public static string ToFolderName(object value) return value.GetType().Name; // TODO if (value is TimeInterval interval) return interval.Nanoseconds + "ns"; - + return value.ToString(); } @@ -43,7 +43,7 @@ public static string ToFolderName(object value) // example: typeof(List).FullName => "System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]" public static string ToFolderName(Type type, bool includeNamespace = true, bool includeGenericArgumentsNamespace = false) => Escape(new StringBuilder(type.GetCorrectCSharpTypeName(includeNamespace, includeGenericArgumentsNamespace))); - + private static string Escape(StringBuilder builder) { foreach (char invalidPathChar in Path.GetInvalidFileNameChars()) diff --git a/src/BenchmarkDotNet/Helpers/FrameworkVersionHelper.cs b/src/BenchmarkDotNet/Helpers/FrameworkVersionHelper.cs index 802ae8e402..7eb3f7e7d9 100644 --- a/src/BenchmarkDotNet/Helpers/FrameworkVersionHelper.cs +++ b/src/BenchmarkDotNet/Helpers/FrameworkVersionHelper.cs @@ -73,7 +73,7 @@ internal static string GetLatestNetDeveloperPackVersion() .FirstOrDefault(v => releaseNumber >= v.minReleaseNumber && IsDeveloperPackInstalled(v.version)) .version; } - + // Reference Assemblies exists when Developer Pack is installed private static bool IsDeveloperPackInstalled(string version) => Directory.Exists(Path.Combine( ProgramFilesX86DirectoryPath, @"Reference Assemblies\Microsoft\Framework\.NETFramework", 'v' + version)); diff --git a/src/BenchmarkDotNet/Helpers/GenericBenchmarksBuilder.cs b/src/BenchmarkDotNet/Helpers/GenericBenchmarksBuilder.cs index 3ca5ee91cb..7e000f6423 100644 --- a/src/BenchmarkDotNet/Helpers/GenericBenchmarksBuilder.cs +++ b/src/BenchmarkDotNet/Helpers/GenericBenchmarksBuilder.cs @@ -20,16 +20,16 @@ internal static Type[] GetRunnableBenchmarks(IEnumerable types) var typeArguments = type.GetCustomAttributes(true).OfType() .Select(x => x.GenericTypeArguments) .ToArray(); - + if (typeArguments.Any()) return BuildGenericTypes(type, typeArguments); - + return new (bool isSuccess, Type result)[] { (true, type) }; } - + private static IEnumerable<(bool isSuccess, Type result)> BuildGenericTypes(Type type, IEnumerable typeArguments) => typeArguments.Select(genericArg => (type.TryMakeGenericType(genericArg, out var builtType), builtType)); - + private static bool TryMakeGenericType(this Type type, Type[] typeArguments, out Type result) { try diff --git a/src/BenchmarkDotNet/Helpers/MultiEncodingString.cs b/src/BenchmarkDotNet/Helpers/MultiEncodingString.cs index 29e56d4f85..5446de1210 100644 --- a/src/BenchmarkDotNet/Helpers/MultiEncodingString.cs +++ b/src/BenchmarkDotNet/Helpers/MultiEncodingString.cs @@ -10,7 +10,7 @@ namespace BenchmarkDotNet.Helpers public class MultiEncodingString { private readonly Dictionary encodedStrings; - + /// Ctor for ascii-only presentation [PublicAPI] public MultiEncodingString(string asciiPresentation) { @@ -18,11 +18,11 @@ [PublicAPI] public MultiEncodingString(string asciiPresentation) { new KeyValuePair(Encoding.ASCII, asciiPresentation) }; - + encodedStrings = pairs.ToDictionary(_ => _.Key.EncodingName, _ => _.Value); } - + /// Ctor for specified unicode and ascii presentations [PublicAPI] public MultiEncodingString(string asciiPresentation, string unicodePresentation) { @@ -31,7 +31,7 @@ [PublicAPI] public MultiEncodingString(string asciiPresentation, string unicodeP new KeyValuePair(Encoding.Unicode, unicodePresentation), new KeyValuePair(Encoding.ASCII, asciiPresentation) }; - + encodedStrings = pairs.ToDictionary(_ => _.Key.EncodingName, _ => _.Value); } @@ -40,12 +40,12 @@ [PublicAPI] public MultiEncodingString(string asciiPresentation, string unicodeP public MultiEncodingString(IEnumerable> encodedStrings) { var sourceStrings = encodedStrings ?? System.Array.Empty>(); - + this.encodedStrings = sourceStrings.Where(kvp => kvp.Value != null) .ToDictionary(_ => _.Key.EncodingName, _ => _.Value); } - + public override string ToString() => GetString(Encoding.ASCII); public string ToString(Encoding encoding) => GetStringByEncoding(encoding); @@ -53,10 +53,10 @@ public MultiEncodingString(IEnumerable> encodedSt [PublicAPI] public string GetString(Encoding encoding) => GetStringByEncoding(encoding); public static implicit operator MultiEncodingString(string s) => new MultiEncodingString(s); - + public static implicit operator MultiEncodingString((string unicodeString, string asciiString) tuple) => new MultiEncodingString(tuple.unicodeString, tuple.asciiString); - + public override bool Equals(object obj) { if (!(obj is MultiEncodingString otherMes)) @@ -66,27 +66,27 @@ public override bool Equals(object obj) && encodedStrings.All(p => otherMes.encodedStrings.ContainsKey(p.Key) && otherMes.encodedStrings[p.Key] == p.Value); } - + public override int GetHashCode() { return encodedStrings .Aggregate(0, (current, encodedString) => current ^ encodedString.Key.GetHashCode() + encodedString.Value.GetHashCode()); } - + private string GetStringByEncoding(Encoding encoding) { if (encoding == null) encoding = GetFallback(); - + if (encodedStrings.TryGetValue(encoding.EncodingName, out string encodedString)) return encodedString; - + return encodedStrings.TryGetValue(GetFallback().EncodingName, out encodedString) ? encodedString : null; } - + private static Encoding GetFallback() => Encoding.ASCII; } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Helpers/SourceCodeHelper.cs b/src/BenchmarkDotNet/Helpers/SourceCodeHelper.cs index a2cfebf4dc..e7fee98461 100644 --- a/src/BenchmarkDotNet/Helpers/SourceCodeHelper.cs +++ b/src/BenchmarkDotNet/Helpers/SourceCodeHelper.cs @@ -39,7 +39,7 @@ public static string ToSourceCode(object value) return "typeof(" + type.GetCorrectCSharpTypeName() + ")"; if (!ReflectionUtils.GetTypeInfo(value.GetType()).IsValueType) return "System.Activator.CreateInstance<" + value.GetType().GetCorrectCSharpTypeName() + ">()"; - + switch (value) { case TimeInterval interval: return "new BenchmarkDotNet.Horology.TimeInterval(" + ToSourceCode(interval.Nanoseconds) + ")"; @@ -52,7 +52,7 @@ public static string ToSourceCode(object value) return value.ToString(); } - public static bool IsCompilationTimeConstant(object value) + public static bool IsCompilationTimeConstant(object value) => value == null || IsCompilationTimeConstant(value.GetType()); public static bool IsCompilationTimeConstant(Type type) @@ -109,7 +109,7 @@ private static string ToSourceCode(double value) return "System.Double.MaxValue"; if (value == double.MinValue) return "System.Double.MinValue"; - + return value.ToString("G", CultureInfo.InvariantCulture) + "d"; } @@ -127,7 +127,7 @@ private static string ToSourceCode(float value) return "System.Single.MaxValue"; if (value == float.MinValue) return "System.Single.MinValue"; - + return value.ToString("G", CultureInfo.InvariantCulture) + "f"; } diff --git a/src/BenchmarkDotNet/Helpers/UserInteractionHelper.cs b/src/BenchmarkDotNet/Helpers/UserInteractionHelper.cs index 88c271b67c..7951d168dd 100644 --- a/src/BenchmarkDotNet/Helpers/UserInteractionHelper.cs +++ b/src/BenchmarkDotNet/Helpers/UserInteractionHelper.cs @@ -10,7 +10,7 @@ internal static class UserInteractionHelper /// (read more here: https://www.shellscript.sh/escape.html). /// /// This method escapes such characters on non-Windows platforms. - /// + /// /// /// /// See also: diff --git a/src/BenchmarkDotNet/Horology/Frequency.cs b/src/BenchmarkDotNet/Horology/Frequency.cs index 4176cbf851..feaaaed336 100644 --- a/src/BenchmarkDotNet/Horology/Frequency.cs +++ b/src/BenchmarkDotNet/Horology/Frequency.cs @@ -41,19 +41,19 @@ [PublicAPI] public Frequency(double value, FrequencyUnit unit) : this(value * un [PublicAPI, Pure] public static Frequency operator *(Frequency a, int k) => new Frequency(a.Hertz * k); [PublicAPI, Pure] public static Frequency operator *(double k, Frequency a) => new Frequency(a.Hertz * k); [PublicAPI, Pure] public static Frequency operator *(int k, Frequency a) => new Frequency(a.Hertz * k); - + [PublicAPI, Pure] public static bool TryParse(string s, FrequencyUnit unit, out Frequency freq) { bool success = double.TryParse(s, NumberStyles.Any, HostEnvironmentInfo.MainCultureInfo, out double result); freq = new Frequency(result, unit); return success; } - + [PublicAPI, Pure] public static bool TryParseHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.Hz, out freq); [PublicAPI, Pure] public static bool TryParseKHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.KHz, out freq); [PublicAPI, Pure] public static bool TryParseMHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.MHz, out freq); [PublicAPI, Pure] public static bool TryParseGHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.GHz, out freq); - + [PublicAPI, Pure] public override string ToString() => Hertz + " " + FrequencyUnit.Hz.Name; } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Horology/FrequencyUnit.cs b/src/BenchmarkDotNet/Horology/FrequencyUnit.cs index cc2efe60ba..49168ca520 100644 --- a/src/BenchmarkDotNet/Horology/FrequencyUnit.cs +++ b/src/BenchmarkDotNet/Horology/FrequencyUnit.cs @@ -12,7 +12,7 @@ private FrequencyUnit(string name, string description, long hertzAmount) Description = description; HertzAmount = hertzAmount; } - + public static readonly FrequencyUnit Hz = new FrequencyUnit("Hz", "Hertz", 1); public static readonly FrequencyUnit KHz = new FrequencyUnit("KHz", "Kilohertz", 1000); public static readonly FrequencyUnit MHz = new FrequencyUnit("MHz", "Megahertz", 1000 * 1000); diff --git a/src/BenchmarkDotNet/Horology/TimeSpanExtensions.cs b/src/BenchmarkDotNet/Horology/TimeSpanExtensions.cs index 18c0ef33b3..ff509cdb2b 100644 --- a/src/BenchmarkDotNet/Horology/TimeSpanExtensions.cs +++ b/src/BenchmarkDotNet/Horology/TimeSpanExtensions.cs @@ -7,7 +7,7 @@ internal static class TimeSpanExtensions { /// /// Time in the following format: {th}:{mm}:{ss} ({ts} sec) - /// + /// /// where /// {th}: total hours (two digits) /// {mm}: minutes (two digits) diff --git a/src/BenchmarkDotNet/Horology/TimeUnit.cs b/src/BenchmarkDotNet/Horology/TimeUnit.cs index 77f519eaf7..cca51ec7fc 100644 --- a/src/BenchmarkDotNet/Horology/TimeUnit.cs +++ b/src/BenchmarkDotNet/Horology/TimeUnit.cs @@ -31,7 +31,7 @@ private TimeUnit(MultiEncodingString name, string description, long nanosecondAm [PublicAPI] public static readonly TimeUnit[] All = { Nanosecond, Microsecond, Millisecond, Second, Minute, Hour, Day }; /// - /// This method chooses the best time unit for representing a set of time measurements. + /// This method chooses the best time unit for representing a set of time measurements. /// /// The list of time measurements in nanoseconds. /// Best time unit. diff --git a/src/BenchmarkDotNet/Jobs/EnvironmentMode.cs b/src/BenchmarkDotNet/Jobs/EnvironmentMode.cs index eef12bed5a..bd92387814 100644 --- a/src/BenchmarkDotNet/Jobs/EnvironmentMode.cs +++ b/src/BenchmarkDotNet/Jobs/EnvironmentMode.cs @@ -78,7 +78,7 @@ public IntPtr Affinity /// GcMode /// public GcMode Gc => GcCharacteristic[this]; - + public IReadOnlyList EnvironmentVariables { get => EnvironmentVariablesCharacteristic[this]; diff --git a/src/BenchmarkDotNet/Jobs/GcMode.cs b/src/BenchmarkDotNet/Jobs/GcMode.cs index cb5285b34f..9255423af6 100644 --- a/src/BenchmarkDotNet/Jobs/GcMode.cs +++ b/src/BenchmarkDotNet/Jobs/GcMode.cs @@ -102,8 +102,8 @@ public int HeapAffinitizeMask } /// - /// specify the # of Server GC threads/heaps, must be smaller than the # of logical CPUs the process is allowed to run on, - /// ie, if you don't specifically affinitize your process it means the # of total logical CPUs on the machine; + /// specify the # of Server GC threads/heaps, must be smaller than the # of logical CPUs the process is allowed to run on, + /// ie, if you don't specifically affinitize your process it means the # of total logical CPUs on the machine; /// otherwise this is the # of logical CPUs you affinitized your process to. /// public int HeapCount diff --git a/src/BenchmarkDotNet/Jobs/GcModeExtensions.cs b/src/BenchmarkDotNet/Jobs/GcModeExtensions.cs index 330c4c6444..e7bec68805 100644 --- a/src/BenchmarkDotNet/Jobs/GcModeExtensions.cs +++ b/src/BenchmarkDotNet/Jobs/GcModeExtensions.cs @@ -53,8 +53,8 @@ public static class GcModeExtensions public static GcMode WithRetainVm(this GcMode mode, bool value) => mode.WithCore(m => m.RetainVm = value); /// - /// specify the # of Server GC threads/heaps, must be smaller than the # of logical CPUs the process is allowed to run on, - /// ie, if you don't specifically affinitize your process it means the # of total logical CPUs on the machine; + /// specify the # of Server GC threads/heaps, must be smaller than the # of logical CPUs the process is allowed to run on, + /// ie, if you don't specifically affinitize your process it means the # of total logical CPUs on the machine; /// otherwise this is the # of logical CPUs you affinitized your process to. /// [PublicAPI] diff --git a/src/BenchmarkDotNet/Jobs/InfrastructureMode.cs b/src/BenchmarkDotNet/Jobs/InfrastructureMode.cs index 8df2bc034f..168c78c343 100644 --- a/src/BenchmarkDotNet/Jobs/InfrastructureMode.cs +++ b/src/BenchmarkDotNet/Jobs/InfrastructureMode.cs @@ -16,7 +16,7 @@ public sealed class InfrastructureMode : JobMode public static readonly Characteristic ToolchainCharacteristic = CreateCharacteristic(nameof(Toolchain)); public static readonly Characteristic ClockCharacteristic = CreateCharacteristic(nameof(Clock)); public static readonly Characteristic EngineFactoryCharacteristic = CreateCharacteristic(nameof(EngineFactory)); - public static readonly Characteristic BuildConfigurationCharacteristic = CreateCharacteristic(nameof(BuildConfiguration)); + public static readonly Characteristic BuildConfigurationCharacteristic = CreateCharacteristic(nameof(BuildConfiguration)); public static readonly Characteristic> ArgumentsCharacteristic = CreateCharacteristic>(nameof(Arguments)); public static readonly Characteristic> NuGetReferencesCharacteristic = CreateCharacteristic>(nameof(NuGetReferences)); diff --git a/src/BenchmarkDotNet/Jobs/JobExtensions.cs b/src/BenchmarkDotNet/Jobs/JobExtensions.cs index 3268a2677c..3ca2350e00 100644 --- a/src/BenchmarkDotNet/Jobs/JobExtensions.cs +++ b/src/BenchmarkDotNet/Jobs/JobExtensions.cs @@ -70,8 +70,8 @@ public static class JobExtensions public static Job WithGcRetainVm(this Job job, bool value) => job.WithCore(j => j.Environment.Gc.RetainVm = value); /// - /// specify the # of Server GC threads/heaps, must be smaller than the # of logical CPUs the process is allowed to run on, - /// ie, if you don't specifically affinitize your process it means the # of total logical CPUs on the machine; + /// specify the # of Server GC threads/heaps, must be smaller than the # of logical CPUs the process is allowed to run on, + /// ie, if you don't specifically affinitize your process it means the # of total logical CPUs on the machine; /// otherwise this is the # of logical CPUs you affinitized your process to. /// [PublicAPI] @@ -230,7 +230,7 @@ public static Job With(this Job job, IReadOnlyList environm /// The original job /// The new environment variable which should be added for the new job /// The new job with additional environment variable - public static Job With(this Job job, EnvironmentVariable environmentVariable) + public static Job With(this Job job, EnvironmentVariable environmentVariable) => job.WithCore(j => j.Environment.SetEnvironmentVariable(environmentVariable)); /// @@ -253,7 +253,7 @@ public static Job WithEnvironmentVariable(this Job job, [NotNull] string key, [N public static Job WithoutEnvironmentVariables(this Job job) => job.With(Array.Empty()); public static Job With(this Job job, IReadOnlyList arguments) => job.WithCore(j => j.Infrastructure.Arguments = arguments); - + /// /// Runs the job with a specific NuGet dependency which will be resolved during the Job build process /// @@ -336,7 +336,7 @@ public static Job WithRemoveOutliers(this Job job, bool value) => /// mutator job should not be added to the config, but instead applied to other jobs in given config /// public static Job AsMutator(this Job job) => job.WithCore(j => j.Meta.IsMutator = true); - + /// /// use it if you want to specify custom default settings for default job used by console arguments parser /// diff --git a/src/BenchmarkDotNet/Jobs/JobIdGenerator.cs b/src/BenchmarkDotNet/Jobs/JobIdGenerator.cs index c57ea840b4..fa8796d112 100644 --- a/src/BenchmarkDotNet/Jobs/JobIdGenerator.cs +++ b/src/BenchmarkDotNet/Jobs/JobIdGenerator.cs @@ -9,7 +9,7 @@ public static string GenerateRandomId(Job job) { string presentation = CharacteristicSetPresenter.Display.ToPresentation(job); if (presentation == "") - return "DefaultJob"; + return "DefaultJob"; int seed = presentation.GetHashCode(); var random = new Random(seed); string id = ""; diff --git a/src/BenchmarkDotNet/Jobs/MetaMode.cs b/src/BenchmarkDotNet/Jobs/MetaMode.cs index 7484ac7b60..d43db3b96b 100644 --- a/src/BenchmarkDotNet/Jobs/MetaMode.cs +++ b/src/BenchmarkDotNet/Jobs/MetaMode.cs @@ -14,7 +14,7 @@ public bool Baseline get => BaselineCharacteristic[this]; set => BaselineCharacteristic[this] = value; } - + /// /// mutator job should not be added to the config, but instead applied to other jobs in given config /// @@ -23,7 +23,7 @@ public bool IsMutator get => IsMutatorCharacteristic[this]; set => IsMutatorCharacteristic[this] = value; } - + /// /// set to true if you want to specify custom default settings for default job used by console arguments parser /// diff --git a/src/BenchmarkDotNet/Jobs/NugetReference.cs b/src/BenchmarkDotNet/Jobs/NugetReference.cs index 8f7f4e9651..d9252c6ed7 100644 --- a/src/BenchmarkDotNet/Jobs/NugetReference.cs +++ b/src/BenchmarkDotNet/Jobs/NugetReference.cs @@ -17,7 +17,7 @@ public NuGetReference(string packageName, string packageVersion) throw new InvalidOperationException($"Invalid version specified: {packageVersion}"); PackageVersion = packageVersion; - + } public string PackageName { get; } diff --git a/src/BenchmarkDotNet/Jobs/RunMode.cs b/src/BenchmarkDotNet/Jobs/RunMode.cs index 7a498027e4..63e72fb487 100644 --- a/src/BenchmarkDotNet/Jobs/RunMode.cs +++ b/src/BenchmarkDotNet/Jobs/RunMode.cs @@ -21,7 +21,7 @@ public sealed class RunMode : JobMode public static readonly Characteristic WarmupCountCharacteristic = CreateCharacteristic(nameof(WarmupCount)); public static readonly Characteristic MinWarmupIterationCountCharacteristic = CreateCharacteristic(nameof(MinWarmupIterationCount)); public static readonly Characteristic MaxWarmupIterationCountCharacteristic = CreateCharacteristic(nameof(MaxWarmupIterationCount)); - + public static readonly RunMode Dry = new RunMode(nameof(Dry)) { LaunchCount = 1, @@ -138,7 +138,7 @@ public int UnrollFactor get { return UnrollFactorCharacteristic[this]; } set { UnrollFactorCharacteristic[this] = value; } } - + /// /// Minimum count of target iterations that should be performed /// The default value is 15 @@ -160,7 +160,7 @@ public int MaxIterationCount get { return MaxIterationCountCharacteristic[this]; } set { MaxIterationCountCharacteristic[this] = value; } } - + /// /// Minimum count of warmup iterations that should be performed /// The default value is 6 diff --git a/src/BenchmarkDotNet/Loggers/LoggerWithPrefix.cs b/src/BenchmarkDotNet/Loggers/LoggerWithPrefix.cs index 831550fc48..ef03335c4e 100644 --- a/src/BenchmarkDotNet/Loggers/LoggerWithPrefix.cs +++ b/src/BenchmarkDotNet/Loggers/LoggerWithPrefix.cs @@ -21,7 +21,7 @@ public void Write(LogKind logKind, string text) { var lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.None); WriteSimple(logKind, lines[0]); - + for (int i = 1; i < lines.Length; i++) { WriteLine(); diff --git a/src/BenchmarkDotNet/Loggers/SynchronousProcessOutputLoggerWithDiagnoser.cs b/src/BenchmarkDotNet/Loggers/SynchronousProcessOutputLoggerWithDiagnoser.cs index 74aec0a989..3e25afc007 100644 --- a/src/BenchmarkDotNet/Loggers/SynchronousProcessOutputLoggerWithDiagnoser.cs +++ b/src/BenchmarkDotNet/Loggers/SynchronousProcessOutputLoggerWithDiagnoser.cs @@ -44,7 +44,7 @@ internal void ProcessInput() if (line == null) continue; - + logger.WriteLine(LogKind.Default, line); if (!line.StartsWith("//")) diff --git a/src/BenchmarkDotNet/Mathematics/BinomialCoefficientHelper.cs b/src/BenchmarkDotNet/Mathematics/BinomialCoefficientHelper.cs index 9ed8749133..5de218f4a4 100644 --- a/src/BenchmarkDotNet/Mathematics/BinomialCoefficientHelper.cs +++ b/src/BenchmarkDotNet/Mathematics/BinomialCoefficientHelper.cs @@ -5,12 +5,12 @@ namespace BenchmarkDotNet.Mathematics public static class BinomialCoefficientHelper { public const int MaxAcceptableN = 65; - + private static long[,] pascalTriangle; public static long GetBinomialCoefficient(int n, int k) { - const int maxN = MaxAcceptableN; + const int maxN = MaxAcceptableN; if (n < 0 || n > maxN) throw new ArgumentOutOfRangeException(nameof(n)); if (k < 0 || k > n) @@ -29,7 +29,7 @@ public static long GetBinomialCoefficient(int n, int k) } } } - + return pascalTriangle[n, k]; } } diff --git a/src/BenchmarkDotNet/Mathematics/Histograms/AdaptiveHistogramBuilder.cs b/src/BenchmarkDotNet/Mathematics/Histograms/AdaptiveHistogramBuilder.cs index 5efaaa46ec..b053a4e1b1 100644 --- a/src/BenchmarkDotNet/Mathematics/Histograms/AdaptiveHistogramBuilder.cs +++ b/src/BenchmarkDotNet/Mathematics/Histograms/AdaptiveHistogramBuilder.cs @@ -33,7 +33,7 @@ public Histogram BuildWithFixedBinSize(IEnumerable values, double binSiz if (binSize < Resolution) binSize = Resolution; binSize = NiceCeiling(binSize); - + var list = values.ToList(); if (list.IsEmpty()) throw new ArgumentException("Values should be non-empty", nameof(values)); diff --git a/src/BenchmarkDotNet/Mathematics/Histograms/BinSizeRule.cs b/src/BenchmarkDotNet/Mathematics/Histograms/BinSizeRule.cs index 399e4c48ce..e63427312a 100644 --- a/src/BenchmarkDotNet/Mathematics/Histograms/BinSizeRule.cs +++ b/src/BenchmarkDotNet/Mathematics/Histograms/BinSizeRule.cs @@ -3,15 +3,15 @@ public enum BinSizeRule { FreedmanDiaconis, - + Scott, - + Scott2, - + SquareRoot, - + Sturges, - + Rice } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Mathematics/Histograms/IHistogramBuilder.cs b/src/BenchmarkDotNet/Mathematics/Histograms/IHistogramBuilder.cs index eab289a6e1..52ff77c7d5 100644 --- a/src/BenchmarkDotNet/Mathematics/Histograms/IHistogramBuilder.cs +++ b/src/BenchmarkDotNet/Mathematics/Histograms/IHistogramBuilder.cs @@ -7,7 +7,7 @@ public interface IHistogramBuilder { [PublicAPI, Pure, NotNull] Histogram Build(Statistics s, BinSizeRule? rule = null); - + [PublicAPI, Pure, NotNull] Histogram BuildWithFixedBinSize(IEnumerable values, double binSize); } diff --git a/src/BenchmarkDotNet/Mathematics/Histograms/SimpleHistogramBuilder.cs b/src/BenchmarkDotNet/Mathematics/Histograms/SimpleHistogramBuilder.cs index cd8f19ccc3..58f8fe887b 100644 --- a/src/BenchmarkDotNet/Mathematics/Histograms/SimpleHistogramBuilder.cs +++ b/src/BenchmarkDotNet/Mathematics/Histograms/SimpleHistogramBuilder.cs @@ -6,7 +6,7 @@ namespace BenchmarkDotNet.Mathematics.Histograms { - internal class SimpleHistogramBuilder : IHistogramBuilder + internal class SimpleHistogramBuilder : IHistogramBuilder { [PublicAPI, Pure] public Histogram Build(Statistics s, BinSizeRule? rule = null) @@ -20,11 +20,11 @@ public Histogram BuildWithFixedBinSize(IEnumerable values, double binSiz { if (binSize < 1e-9) throw new ArgumentException($"binSize ({binSize.ToStr()}) should be a positive number", nameof(binSize)); - + var list = values.ToList(); if (list.IsEmpty()) throw new ArgumentException("Values should be non-empty", nameof(values)); - + list.Sort(); int firstBin = GetBinIndex(list.First(), binSize); diff --git a/src/BenchmarkDotNet/Mathematics/MathHelper.cs b/src/BenchmarkDotNet/Mathematics/MathHelper.cs index 6231814ec7..eaf6f26e78 100644 --- a/src/BenchmarkDotNet/Mathematics/MathHelper.cs +++ b/src/BenchmarkDotNet/Mathematics/MathHelper.cs @@ -12,13 +12,13 @@ public static class MathHelper { /// /// ACM Algorithm 209: Gauss - /// + /// /// Calculates $(1/\sqrt{2\pi}) \int_{-\infty}^x e^{-u^2 / 2} du$ /// by means of polynomial approximations due to A. M. Murray of Aberdeen University; - /// + /// /// See: http://dl.acm.org/citation.cfm?id=367664 - /// - /// -infinity..+infinity + /// + /// -infinity..+infinity /// Area under the Standard Normal Curve from -infinity to x [PublicAPI] public static double Gauss(double x) @@ -54,10 +54,10 @@ public static double Gauss(double x) /// /// ACM Algorithm 395: Student's t-distribution - /// - /// Evaluates the two-tail probability P(t|n) that t is exceeded + /// + /// Evaluates the two-tail probability P(t|n) that t is exceeded /// in magnitude for Student's t-distribution with n degrees of freedom. - /// + /// /// http://dl.acm.org/citation.cfm?id=355599 /// /// t-value, t > 0 diff --git a/src/BenchmarkDotNet/Mathematics/MeasurementsStatistics.cs b/src/BenchmarkDotNet/Mathematics/MeasurementsStatistics.cs index 395df056ac..558e352371 100644 --- a/src/BenchmarkDotNet/Mathematics/MeasurementsStatistics.cs +++ b/src/BenchmarkDotNet/Mathematics/MeasurementsStatistics.cs @@ -152,7 +152,7 @@ private static bool IsOutlier(OutlierMode outlierMode, double value, double lowe #pragma warning restore 618 default: throw new ArgumentOutOfRangeException(nameof(outlierMode), outlierMode, null); - } + } } } } diff --git a/src/BenchmarkDotNet/Mathematics/NumeralSystem.cs b/src/BenchmarkDotNet/Mathematics/NumeralSystem.cs index 866d2a44cc..7fe2be2664 100644 --- a/src/BenchmarkDotNet/Mathematics/NumeralSystem.cs +++ b/src/BenchmarkDotNet/Mathematics/NumeralSystem.cs @@ -6,12 +6,12 @@ public enum NumeralSystem /// Arabic numerals (1, 2, 3, 4, ...) /// Arabic, - + /// /// Roman numerals (I, II, III, IV, ...) /// Roman, - + /// /// Unary numeral system (*, **, ***, ****, ...) /// diff --git a/src/BenchmarkDotNet/Mathematics/OutlierMode.cs b/src/BenchmarkDotNet/Mathematics/OutlierMode.cs index 8b5a31d026..91664a50f6 100644 --- a/src/BenchmarkDotNet/Mathematics/OutlierMode.cs +++ b/src/BenchmarkDotNet/Mathematics/OutlierMode.cs @@ -12,40 +12,40 @@ public enum OutlierMode /// [Obsolete("Use DontRemoveOutliers")] None, - + /// /// Remove only upper outliers (which is bigger than upperFence). /// [Obsolete("Use RemoveUpperOutliers")] OnlyUpper, - + /// /// Remove only lower outliers (which is smaller than lowerFence). /// [Obsolete("Use RemoveUpperOutliers")] OnlyLower, - + /// /// Remove all outliers. /// [Obsolete("Use RemoveAllOutliers")] All, - + /// /// Don't remove outliers. /// DontRemove, - + /// /// Remove only upper outliers (which is bigger than upperFence). /// RemoveUpper, - + /// /// Remove only lower outliers (which is smaller than lowerFence). /// RemoveLower, - + /// /// Remove all outliers. /// diff --git a/src/BenchmarkDotNet/Mathematics/PercentileValues.cs b/src/BenchmarkDotNet/Mathematics/PercentileValues.cs index 512b9d0807..b29a5069d3 100644 --- a/src/BenchmarkDotNet/Mathematics/PercentileValues.cs +++ b/src/BenchmarkDotNet/Mathematics/PercentileValues.cs @@ -14,7 +14,7 @@ public class PercentileValues /// /// /// The implementation is expected to be consistent with the one from Excel. - /// It's a quite common to export bench output into .csv for further analysis + /// It's a quite common to export bench output into .csv for further analysis /// And it's a good idea to have same results from all tools being used. /// /// Sequence of the values to be calculated diff --git a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/OneSidedTestResult.cs b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/OneSidedTestResult.cs index 091bff2f94..238a76c8cb 100644 --- a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/OneSidedTestResult.cs +++ b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/OneSidedTestResult.cs @@ -3,16 +3,16 @@ namespace BenchmarkDotNet.Mathematics.StatisticalTesting { public class OneSidedTestResult - { + { public double PValue { get; } public Threshold Threshold { get; } - public bool NullHypothesisIsRejected => PValue < 0.05; + public bool NullHypothesisIsRejected => PValue < 0.05; public OneSidedTestResult(double pValue, Threshold threshold) { PValue = pValue; Threshold = threshold; - } + } public string H0 => Threshold.IsZero() ? "True difference in means is zero" @@ -21,7 +21,7 @@ public OneSidedTestResult(double pValue, Threshold threshold) public string H1 => Threshold.IsZero() ? "True difference in means is greater than zero" : $"True difference in means > {Threshold}"; - + public string PValueStr => PValue.ToStr("N4"); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/StatisticalTestHelper.cs b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/StatisticalTestHelper.cs index 9a3cba94b4..c761a2d458 100644 --- a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/StatisticalTestHelper.cs +++ b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/StatisticalTestHelper.cs @@ -12,13 +12,13 @@ public static TostResult CalculateTost(IOneSidedTest test, double[] bas { if (baseline.SequenceEqual(candidate)) // WelchTest would throw StackoverflowException ;) return new TostResult(threshold, EquivalenceTestConclusion.Base, null, null); - + var fasterTestResult = test.IsGreater(baseline, candidate, threshold); var slowerTestResult = test.IsGreater(candidate, baseline, threshold); EquivalenceTestConclusion conclusion; if (fasterTestResult == null || slowerTestResult == null) - conclusion = EquivalenceTestConclusion.Unknown; + conclusion = EquivalenceTestConclusion.Unknown; else if (fasterTestResult.NullHypothesisIsRejected) conclusion = EquivalenceTestConclusion.Faster; else if (slowerTestResult.NullHypothesisIsRejected) diff --git a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/StudentTest.cs b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/StudentTest.cs index ccd7f61ca3..fb6d69171b 100644 --- a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/StudentTest.cs +++ b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/StudentTest.cs @@ -5,14 +5,14 @@ namespace BenchmarkDotNet.Mathematics.StatisticalTesting public class StudentTest { public static readonly StudentTest Instance = new StudentTest(); - + /// /// Determines whether the sample mean is different from a known mean /// /// Should be consistent with t.test(x, mu = mu, alternative = "greater") from R - public OneSidedTestResult IsGreater(double[] sample, double value, Threshold threshold = null) + public OneSidedTestResult IsGreater(double[] sample, double value, Threshold threshold = null) => IsGreater(new Statistics(sample), value, threshold); - + /// /// Determines whether the sample mean is different from a known mean /// @@ -23,13 +23,13 @@ public OneSidedTestResult IsGreater(Statistics sample, double value, Threshold t double stdDev = sample.StandardDeviation; double n = sample.N; double df = n - 1; - + threshold = threshold ?? RelativeThreshold.Default; - double t = (mean - value) / + double t = (mean - value) / (stdDev / Math.Sqrt(n)); double pValue = 1 - MathHelper.StudentOneTail(t, df); - + return new OneSidedTestResult(pValue, threshold); } } diff --git a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/Threshold.cs b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/Threshold.cs index 9eba3e3d6b..411a85a308 100644 --- a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/Threshold.cs +++ b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/Threshold.cs @@ -30,7 +30,7 @@ public static bool TryParse(string input, out Threshold parsed) parsed = default; return false; } - + var trimmed = input.Trim().ToLowerInvariant(); var number = new string(trimmed.TakeWhile(c => char.IsDigit(c) || c == '.' || c == ',').ToArray()); var unit = new string(trimmed.SkipWhile(c => char.IsDigit(c) || c == '.' || c == ',' || char.IsWhiteSpace(c)).ToArray()); diff --git a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/ThresholdUnit.cs b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/ThresholdUnit.cs index 074f2c616b..40f9a4c31d 100644 --- a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/ThresholdUnit.cs +++ b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/ThresholdUnit.cs @@ -26,7 +26,7 @@ internal static class ThresholdUnitExtensions { ThresholdUnit.Minutes, "m" }, }; - internal static readonly IReadOnlyDictionary ShortNameToUnit = UnitToShortName.ToDictionary(pair => pair.Value, pair => pair.Key); + internal static readonly IReadOnlyDictionary ShortNameToUnit = UnitToShortName.ToDictionary(pair => pair.Value, pair => pair.Key); internal static string ToShortName(this ThresholdUnit thresholdUnit) => UnitToShortName[thresholdUnit]; } diff --git a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/WelchResult.cs b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/WelchResult.cs index f8e6ddb208..5de8d35fef 100644 --- a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/WelchResult.cs +++ b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/WelchResult.cs @@ -3,7 +3,7 @@ public class WelchResult : OneSidedTestResult { public double T { get; } - public double Df { get; } + public double Df { get; } public WelchResult(double x, double df, double pValue, Threshold threshold) : base(pValue, threshold) { diff --git a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/WelchTest.cs b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/WelchTest.cs index 5fe1610f2c..896828bcf0 100644 --- a/src/BenchmarkDotNet/Mathematics/StatisticalTesting/WelchTest.cs +++ b/src/BenchmarkDotNet/Mathematics/StatisticalTesting/WelchTest.cs @@ -7,7 +7,7 @@ namespace BenchmarkDotNet.Mathematics.StatisticalTesting public class WelchTest : IOneSidedTest { public static readonly WelchTest Instance = new WelchTest(); - + /// /// Checks that (x-y) > threshold /// diff --git a/src/BenchmarkDotNet/Mathematics/Statistics.cs b/src/BenchmarkDotNet/Mathematics/Statistics.cs index d4a11410eb..d8b8c2b1fc 100644 --- a/src/BenchmarkDotNet/Mathematics/Statistics.cs +++ b/src/BenchmarkDotNet/Mathematics/Statistics.cs @@ -154,17 +154,17 @@ public override string ToString() /// /// Statistics for [1/X]. If Min is less then or equal to 0, returns null. - /// + /// public Statistics Invert() => CanBeInverted() ? new Statistics(SortedValues.Select(x => 1 / x)) : null; /// /// Mean for [X*Y]. - /// + /// public static double MulMean(Statistics x, Statistics y) => x.Mean * y.Mean; /// /// Mean for [X/Y]. - /// + /// public static double DivMean([CanBeNull] Statistics x, [CanBeNull] Statistics y) { if (x == null || y == null) diff --git a/src/BenchmarkDotNet/Order/DefaultOrderer.cs b/src/BenchmarkDotNet/Order/DefaultOrderer.cs index debc9f951a..e03364c4e6 100644 --- a/src/BenchmarkDotNet/Order/DefaultOrderer.cs +++ b/src/BenchmarkDotNet/Order/DefaultOrderer.cs @@ -25,7 +25,7 @@ public class DefaultOrderer : IOrderer public MethodOrderPolicy MethodOrderPolicy { get; } public DefaultOrderer( - SummaryOrderPolicy summaryOrderPolicy = SummaryOrderPolicy.Default, + SummaryOrderPolicy summaryOrderPolicy = SummaryOrderPolicy.Default, MethodOrderPolicy methodOrderPolicy = MethodOrderPolicy.Declared) { SummaryOrderPolicy = summaryOrderPolicy; @@ -50,9 +50,9 @@ public virtual IEnumerable GetSummaryOrder(ImmutableArray GetSummaryOrderForGroup(ImmutableArray benchmarksCase, Summary summary) - { + { switch (SummaryOrderPolicy) { case SummaryOrderPolicy.FastestToSlowest: @@ -90,7 +90,7 @@ public string GetLogicalGroupKey(ImmutableArray allBenchmarksCase { rules.Add(BenchmarkLogicalGroupRule.ByMethod); rules.Add(BenchmarkLogicalGroupRule.ByParams); - } + } if (hasDescriptorBaselines) { rules.Add(BenchmarkLogicalGroupRule.ByJob); @@ -102,7 +102,7 @@ public string GetLogicalGroupKey(ImmutableArray allBenchmarksCase rules.Remove(BenchmarkLogicalGroupRule.ByJob); } - var keys = new List(); + var keys = new List(); if (rules.Contains(BenchmarkLogicalGroupRule.ByMethod)) keys.Add(benchmarkCase.Descriptor.DisplayInfo); if (rules.Contains(BenchmarkLogicalGroupRule.ByJob)) diff --git a/src/BenchmarkDotNet/Order/IOrderer.cs b/src/BenchmarkDotNet/Order/IOrderer.cs index 776636e657..f961cf31b2 100644 --- a/src/BenchmarkDotNet/Order/IOrderer.cs +++ b/src/BenchmarkDotNet/Order/IOrderer.cs @@ -24,7 +24,7 @@ public interface IOrderer [PublicAPI, NotNull] IEnumerable> GetLogicalGroupOrder(IEnumerable> logicalGroups); - + [PublicAPI] bool SeparateLogicalGroups { get; } } diff --git a/src/BenchmarkDotNet/Parameters/ParameterInstance.cs b/src/BenchmarkDotNet/Parameters/ParameterInstance.cs index 073fae7630..31a0396f6c 100644 --- a/src/BenchmarkDotNet/Parameters/ParameterInstance.cs +++ b/src/BenchmarkDotNet/Parameters/ParameterInstance.cs @@ -12,7 +12,7 @@ public class ParameterInstance private const int MaxDisplayTextInnerLength = 15 + 5; // 5 is for postfix " [15]" [PublicAPI] public ParameterDefinition Definition { get; } - + private readonly object value; public ParameterInstance(ParameterDefinition definition, object value) @@ -27,8 +27,8 @@ public ParameterInstance(ParameterDefinition definition, object value) public object Value => value is IParam parameter ? parameter.Value : value; - public string ToSourceCode() - => value is IParam parameter + public string ToSourceCode() + => value is IParam parameter ? parameter.ToSourceCode() : SourceCodeHelper.ToSourceCode(value); @@ -49,7 +49,7 @@ public string ToDisplayText() public override string ToString() => ToDisplayText(); - private static string Trim(string value) + private static string Trim(string value) => value.Length <= MaxDisplayTextInnerLength ? value : value.Substring(0, 5) + "(...)" + value.Substring(value.Length - 5, 5) + $" [{value.Length}]"; diff --git a/src/BenchmarkDotNet/Parameters/SmartParamBuilder.cs b/src/BenchmarkDotNet/Parameters/SmartParamBuilder.cs index 45044a955d..c8916543b4 100644 --- a/src/BenchmarkDotNet/Parameters/SmartParamBuilder.cs +++ b/src/BenchmarkDotNet/Parameters/SmartParamBuilder.cs @@ -26,7 +26,7 @@ internal static ParameterInstances CreateForArguments(MethodInfo benchmark, Para if (unwrappedValue is object[] array) { // the user provided object[] for a benchmark accepting a single argument - if (parameterDefinitions.Length == 1 && array.Length == 1 + if (parameterDefinitions.Length == 1 && array.Length == 1 && array[0].GetType() == benchmark.GetParameters().FirstOrDefault()?.ParameterType) // the benchmark that accepts an object[] as argument { return new ParameterInstances( @@ -87,13 +87,13 @@ public string ToSourceCode() string callPostfix = source is PropertyInfo ? string.Empty : "()"; - string indexPostfix = parameterDefinitions.Length > 1 - ? $"[{argumentIndex}]" // IEnumerable + string indexPostfix = parameterDefinitions.Length > 1 + ? $"[{argumentIndex}]" // IEnumerable : string.Empty; // IEnumerable - // we just execute (cast)source.ToArray()[case][argumentIndex]; + // we just execute (cast)source.ToArray()[case][argumentIndex]; // we know that source is IEnumerable so we can do that! - return $"{cast}System.Linq.Enumerable.ToArray({source.Name}{callPostfix})[{sourceIndex}]{indexPostfix};"; + return $"{cast}System.Linq.Enumerable.ToArray({source.Name}{callPostfix})[{sourceIndex}]{indexPostfix};"; } } @@ -123,7 +123,7 @@ public string ToSourceCode() string callPostfix = source is PropertyInfo ? string.Empty : "()"; - // we just execute (cast)source.ToArray()[index]; + // we just execute (cast)source.ToArray()[index]; return $"{cast}System.Linq.Enumerable.ToArray({instancePrefix}.{source.Name}{callPostfix})[{index}];"; } } diff --git a/src/BenchmarkDotNet/Portability/Cpu/CpuInfo.cs b/src/BenchmarkDotNet/Portability/Cpu/CpuInfo.cs index 43b235363c..635f3c1c6d 100644 --- a/src/BenchmarkDotNet/Portability/Cpu/CpuInfo.cs +++ b/src/BenchmarkDotNet/Portability/Cpu/CpuInfo.cs @@ -16,7 +16,7 @@ internal CpuInfo(string processorName, Frequency? nominalFrequency) : this(processorName, null, null, null, nominalFrequency, null, null) { } - + public CpuInfo(string processorName, int? physicalProcessorCount, int? physicalCoreCount, diff --git a/src/BenchmarkDotNet/Portability/Cpu/CpuInfoFormatter.cs b/src/BenchmarkDotNet/Portability/Cpu/CpuInfoFormatter.cs index b9246397ed..e016ad1a4b 100644 --- a/src/BenchmarkDotNet/Portability/Cpu/CpuInfoFormatter.cs +++ b/src/BenchmarkDotNet/Portability/Cpu/CpuInfoFormatter.cs @@ -11,7 +11,7 @@ public static string Format(CpuInfo cpuInfo) { return "Unknown processor"; } - + var parts = new List { ProcessorBrandStringHelper.Prettify(cpuInfo, includeMaxFrequency: true) @@ -35,7 +35,7 @@ public static string Format(CpuInfo cpuInfo) parts.Add("1 physical core"); if (cpuInfo.PhysicalCoreCount > 1) parts.Add($"{cpuInfo.PhysicalCoreCount} physical cores"); - + string result = string.Join("", parts); // The line with ProcessorBrandString is one of the longest lines in the summary. // When people past in on GitHub, it can be a reason of an ugly horizontal scrollbar. diff --git a/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoParser.cs b/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoParser.cs index 0bd7c31695..0ed00b129d 100644 --- a/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoParser.cs +++ b/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoParser.cs @@ -15,12 +15,12 @@ internal static CpuInfo ParseOutput([CanBeNull] string content) var logicalCores = SectionsHelper.ParseSections(content, ':'); var processorModelNames = new HashSet(); var processorsToPhysicalCoreCount = new Dictionary(); - + int logicalCoreCount = 0; var nominalFrequency = Frequency.Zero; var minFrequency = Frequency.Zero; var maxFrequency = Frequency.Zero; - + foreach (var logicalCore in logicalCores) { if (logicalCore.TryGetValue(ProcCpuInfoKeyNames.PhysicalId, out string physicalId) && @@ -35,13 +35,13 @@ internal static CpuInfo ParseOutput([CanBeNull] string content) nominalFrequency = ParseFrequencyFromBrandString(modelName); logicalCoreCount++; } - + if (logicalCore.TryGetValue(ProcCpuInfoKeyNames.MinFrequency, out string minCpuFreqValue) && Frequency.TryParseMHz(minCpuFreqValue, out var minCpuFreq)) { minFrequency = minCpuFreq; } - + if (logicalCore.TryGetValue(ProcCpuInfoKeyNames.MaxFrequency, out string maxCpuFreqValue) && Frequency.TryParseMHz(maxCpuFreqValue, out var maxCpuFreq)) { diff --git a/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoProvider.cs b/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoProvider.cs index c0507ac478..41e3c29651 100644 --- a/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoProvider.cs +++ b/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoProvider.cs @@ -26,7 +26,7 @@ private static CpuInfo Load() } return null; } - + private static string GetCpuSpeed() { var output = ProcessHelper.RunAndReadOutput("/bin/bash", "-c \"lscpu | grep MHz\"")? @@ -51,7 +51,7 @@ private static string ParseCpuFrequencies(string[] input) Frequency.TryParseMHz(input[3].Trim().Replace(',', '.'), out var minFrequency); Frequency.TryParseMHz(input[5].Trim().Replace(',', '.'), out var maxFrequency); - + return $"\n{ProcCpuInfoKeyNames.MinFrequency}\t:{minFrequency.ToMHz()}\n{ProcCpuInfoKeyNames.MaxFrequency}\t:{maxFrequency.ToMHz()}\n"; } } diff --git a/src/BenchmarkDotNet/Portability/Cpu/SysctlCpuInfoParser.cs b/src/BenchmarkDotNet/Portability/Cpu/SysctlCpuInfoParser.cs index f75ef32632..0b3b405baa 100644 --- a/src/BenchmarkDotNet/Portability/Cpu/SysctlCpuInfoParser.cs +++ b/src/BenchmarkDotNet/Portability/Cpu/SysctlCpuInfoParser.cs @@ -32,7 +32,7 @@ internal static CpuInfo ParseOutput([CanBeNull] string content) return result; return null; } - + [CanBeNull] private static long? GetPositiveLongValue([NotNull] Dictionary sysctl, [NotNull] string keyName) { diff --git a/src/BenchmarkDotNet/Portability/Cpu/SysctlCpuInfoProvider.cs b/src/BenchmarkDotNet/Portability/Cpu/SysctlCpuInfoProvider.cs index 893dc74c13..d5aad7136f 100644 --- a/src/BenchmarkDotNet/Portability/Cpu/SysctlCpuInfoProvider.cs +++ b/src/BenchmarkDotNet/Portability/Cpu/SysctlCpuInfoProvider.cs @@ -4,7 +4,7 @@ namespace BenchmarkDotNet.Portability.Cpu { - /// + /// /// CPU information from output of the `sysctl -a` command. /// MacOSX only. /// diff --git a/src/BenchmarkDotNet/Portability/Cpu/WmicCpuInfoParser.cs b/src/BenchmarkDotNet/Portability/Cpu/WmicCpuInfoParser.cs index 878dbeb827..1ead0f6ee7 100644 --- a/src/BenchmarkDotNet/Portability/Cpu/WmicCpuInfoParser.cs +++ b/src/BenchmarkDotNet/Portability/Cpu/WmicCpuInfoParser.cs @@ -16,7 +16,7 @@ internal static CpuInfo ParseOutput([CanBeNull] string content) int physicalCoreCount = 0; int logicalCoreCount = 0; int processorsCount = 0; - + var currentClockSpeed = Frequency.Zero; var maxClockSpeed = Frequency.Zero; var minClockSpeed = Frequency.Zero; @@ -38,8 +38,8 @@ internal static CpuInfo ParseOutput([CanBeNull] string content) processorModelNames.Add(name); processorsCount++; } - - if (processor.TryGetValue(WmicCpuInfoKeyNames.MaxClockSpeed, out string frequencyValue) + + if (processor.TryGetValue(WmicCpuInfoKeyNames.MaxClockSpeed, out string frequencyValue) && int.TryParse(frequencyValue, out int frequency) && frequency > 0) { diff --git a/src/BenchmarkDotNet/Portability/RuntimeInformation.cs b/src/BenchmarkDotNet/Portability/RuntimeInformation.cs index 7e7324d365..0660bf4f75 100644 --- a/src/BenchmarkDotNet/Portability/RuntimeInformation.cs +++ b/src/BenchmarkDotNet/Portability/RuntimeInformation.cs @@ -37,18 +37,18 @@ internal static class RuntimeInformation /// /// "The north star for CoreRT is to be a flavor of .NET Core" -> CoreRT reports .NET Core everywhere /// - public static bool IsCoreRT - => FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase) + public static bool IsCoreRT + => FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(typeof(object).Assembly.Location); // but it's merged to a single .exe and .Location returns null here ;) public static bool IsRunningInContainer => string.Equals(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true"); - + internal static string ExecutableExtension => IsWindows() ? ".exe" : string.Empty; internal static string ScriptFileExtension => IsWindows() ? ".bat" : ".sh"; internal static string GetArchitecture() => GetCurrentPlatform().ToString(); - + internal static bool IsWindows() => IsOSPlatform(OSPlatform.Windows); internal static bool IsLinux() => IsOSPlatform(OSPlatform.Linux); @@ -171,7 +171,7 @@ internal static Runtime GetCurrentRuntime() return CoreRuntime.GetCurrentVersion(); if (IsCoreRT) return CoreRtRuntime.GetCurrentVersion(); - + throw new NotSupportedException("Unknown .NET Runtime"); } diff --git a/src/BenchmarkDotNet/Reports/BenchmarkReport.cs b/src/BenchmarkDotNet/Reports/BenchmarkReport.cs index b3d8f93094..b723e82dcf 100644 --- a/src/BenchmarkDotNet/Reports/BenchmarkReport.cs +++ b/src/BenchmarkDotNet/Reports/BenchmarkReport.cs @@ -37,7 +37,7 @@ public BenchmarkReport( BuildResult buildResult, IReadOnlyList executeResults, IReadOnlyList allMeasurements, - GcStats gcStats, + GcStats gcStats, IReadOnlyList metrics) { Success = success; diff --git a/src/BenchmarkDotNet/Reports/DisplayPrecisionManager.cs b/src/BenchmarkDotNet/Reports/DisplayPrecisionManager.cs index 474bf8406a..fc524299a1 100644 --- a/src/BenchmarkDotNet/Reports/DisplayPrecisionManager.cs +++ b/src/BenchmarkDotNet/Reports/DisplayPrecisionManager.cs @@ -12,7 +12,7 @@ internal class DisplayPrecisionManager { private const int MinPrecision = 1; private const int MaxPrecision = 4; - + private readonly IDictionary precision = new Dictionary(); private readonly Summary summary; diff --git a/src/BenchmarkDotNet/Reports/Measurement.cs b/src/BenchmarkDotNet/Reports/Measurement.cs index 2679b52367..06c6331c25 100644 --- a/src/BenchmarkDotNet/Reports/Measurement.cs +++ b/src/BenchmarkDotNet/Reports/Measurement.cs @@ -16,11 +16,11 @@ public struct Measurement : IComparable { private static Measurement Error (Encoding encoding) => new Measurement(-1, IterationMode.Unknown, IterationStage.Unknown, 0, 0, 0, encoding); - private static readonly int IterationInfoNameMaxWidth + private static readonly int IterationInfoNameMaxWidth = Enum.GetNames(typeof(IterationMode)).Max(text => text.Length) + Enum.GetNames(typeof(IterationStage)).Max(text => text.Length); public IterationMode IterationMode { get; } - + public IterationStage IterationStage { get; } public int LaunchIndex { get; } @@ -39,7 +39,7 @@ private static readonly int IterationInfoNameMaxWidth /// Gets the total number of nanoseconds it took to perform all operations. /// public double Nanoseconds { get; } - + /// /// Creates an instance of struct. /// @@ -64,11 +64,11 @@ public Measurement(int launchIndex, IterationMode iterationMode, IterationStage public string ToOutputLine() { string alignedIterationInfo = (IterationMode.ToString() + IterationStage).PadRight(IterationInfoNameMaxWidth, ' '); - + // Usually, a benchmarks takes more than 10 iterations (rarely more than 99) // PadLeft(2, ' ') looks like a good trade-off between alignment and amount of characters string alignedIterationIndex = IterationIndex.ToString().PadLeft(2, ' '); - + return $"{alignedIterationInfo} {alignedIterationIndex}: {GetDisplayValue()}"; } @@ -77,12 +77,12 @@ public string ToOutputLine() /// /// Parses the benchmark statistics from the plain text line. - /// + /// /// E.g. given the input : - /// + /// /// WorkloadTarget 1: 10 op, 1005842518 ns - /// - /// Will extract the number of performed and the + /// + /// Will extract the number of performed and the /// total number of it took to perform them. /// /// The logger to write any diagnostic messages to. @@ -94,7 +94,7 @@ public static Measurement Parse(ILogger logger, string line, int processIndex, E { if (encoding == null) encoding = Encoding.ASCII; - + if (line == null || line.StartsWith(GcStats.ResultsLinePrefix)) return Error(encoding); @@ -109,13 +109,13 @@ public static Measurement Parse(ILogger logger, string line, int processIndex, E if (char.IsUpper(iterationInfoSplit[0][i])) { iterationStageIndex = i; - break; + break; } string iterationModeStr = iterationInfoSplit[0].Substring(0, iterationStageIndex); string iterationStageStr = iterationInfoSplit[0].Substring(iterationStageIndex); - - + + var iterationMode = ParseIterationMode(iterationModeStr); var iterationStage = ParseIterationStage(iterationStageStr); int.TryParse(iterationInfoSplit[1], out int iterationIndex); diff --git a/src/BenchmarkDotNet/Reports/Metric.cs b/src/BenchmarkDotNet/Reports/Metric.cs index 3e2a6e43e1..ad69edd13e 100644 --- a/src/BenchmarkDotNet/Reports/Metric.cs +++ b/src/BenchmarkDotNet/Reports/Metric.cs @@ -7,7 +7,7 @@ namespace BenchmarkDotNet.Reports public class Metric { public double Value { get; } - + public IMetricDescriptor Descriptor { get; } public Metric(IMetricDescriptor descriptor, double value) @@ -20,7 +20,7 @@ public Metric(IMetricDescriptor descriptor, double value) public interface IMetricDescriptor { [PublicAPI] string Id { get; } - + [PublicAPI] string DisplayName { get; } [PublicAPI] string Legend { get; } @@ -28,7 +28,7 @@ public interface IMetricDescriptor [PublicAPI] string NumberFormat { get; } [PublicAPI] UnitType UnitType { get; } - + [PublicAPI] string Unit { get; } [PublicAPI] bool TheGreaterTheBetter { get; } @@ -37,7 +37,7 @@ public interface IMetricDescriptor public class MetricDescriptorEqualityComparer : EqualityComparer { public static readonly EqualityComparer Instance = new MetricDescriptorEqualityComparer(); - + public override bool Equals(IMetricDescriptor x, IMetricDescriptor y) => x.Id.Equals(y.Id); public override int GetHashCode(IMetricDescriptor obj) => obj.Id.GetHashCode(); diff --git a/src/BenchmarkDotNet/Reports/Summary.cs b/src/BenchmarkDotNet/Reports/Summary.cs index 44a14266b8..00196d49ef 100644 --- a/src/BenchmarkDotNet/Reports/Summary.cs +++ b/src/BenchmarkDotNet/Reports/Summary.cs @@ -24,13 +24,13 @@ public class Summary [PublicAPI] public SummaryTable Table { get; } [PublicAPI] public string AllRuntimes { get; } [PublicAPI] public ImmutableArray ValidationErrors { get; } - + [PublicAPI] public ImmutableArray BenchmarksCases { get; } [PublicAPI] public ImmutableArray Reports { get; } private ImmutableDictionary ReportMap {get; } private BaseliningStrategy BaseliningStrategy {get; } - + internal DisplayPrecisionManager DisplayPrecisionManager { get; } public Summary( @@ -50,12 +50,12 @@ public Summary( ValidationErrors = validationErrors; ReportMap = reports.ToImmutableDictionary(report => report.BenchmarkCase, report => report); - + DisplayPrecisionManager = new DisplayPrecisionManager(this); Orderer = GetConfiguredOrdererOrDefaultOne(reports.Select(report => report.BenchmarkCase.Config)); BenchmarksCases = Orderer.GetSummaryOrder(reports.Select(report => report.BenchmarkCase).ToImmutableArray(), this).ToImmutableArray(); // we sort it first Reports = BenchmarksCases.Select(b => ReportMap[b]).ToImmutableArray(); // we use sorted collection to re-create reports list - BaseliningStrategy = BaseliningStrategy.Create(BenchmarksCases); + BaseliningStrategy = BaseliningStrategy.Create(BenchmarksCases); Style = GetConfiguredSummaryStyleOrNull(BenchmarksCases); Table = GetTable(Style); AllRuntimes = BuildAllRuntimes(HostEnvironmentInfo, Reports); @@ -65,7 +65,7 @@ public Summary( /// /// Returns a report for the given benchmark or null if there is no a corresponded report. - /// + /// public BenchmarkReport this[BenchmarkCase benchmarkCase] => ReportMap.GetValueOrDefault(benchmarkCase); public bool HasCriticalValidationErrors => ValidationErrors.Any(validationError => validationError.IsCritical); @@ -78,11 +78,11 @@ internal static Summary NothingToRun(string title, string resultsDirectoryPath, internal static Summary ValidationFailed(string title, string resultsDirectoryPath, string logFilePath, ImmutableArray validationErrors) => new Summary(title, ImmutableArray.Empty, HostEnvironmentInfo.GetCurrent(), resultsDirectoryPath, logFilePath, TimeSpan.Zero, validationErrors); - internal static Summary Join(List summaries, ClockSpan clockSpan) + internal static Summary Join(List summaries, ClockSpan clockSpan) => new Summary( $"BenchmarkRun-joined-{DateTime.Now:yyyy-MM-dd-hh-mm-ss}", summaries.SelectMany(summary => summary.Reports).ToImmutableArray(), - HostEnvironmentInfo.GetCurrent(), + HostEnvironmentInfo.GetCurrent(), summaries.First().ResultsDirectoryPath, summaries.First().LogFilePath, clockSpan.GetTimeSpan(), @@ -122,17 +122,17 @@ internal static string BuildAllRuntimes(HostEnvironmentInfo hostEnvironmentInfo, public string GetLogicalGroupKey(BenchmarkCase benchmarkCase) => Orderer.GetLogicalGroupKey(BenchmarksCases, benchmarkCase); - public bool IsBaseline(BenchmarkCase benchmarkCase) + public bool IsBaseline(BenchmarkCase benchmarkCase) => BaseliningStrategy.IsBaseline(benchmarkCase); [CanBeNull] - public BenchmarkCase GetBaseline(string logicalGroupKey) + public BenchmarkCase GetBaseline(string logicalGroupKey) => BenchmarksCases .Where(b => GetLogicalGroupKey(b) == logicalGroupKey) .FirstOrDefault(IsBaseline); [NotNull] - public IEnumerable GetNonBaselines(string logicalGroupKey) + public IEnumerable GetNonBaselines(string logicalGroupKey) => BenchmarksCases .Where(b => GetLogicalGroupKey(b) == logicalGroupKey) .Where(b => !IsBaseline(b)); diff --git a/src/BenchmarkDotNet/Reports/SummaryTableExtensions.cs b/src/BenchmarkDotNet/Reports/SummaryTableExtensions.cs index 40d239dca2..f8f8fdc3aa 100644 --- a/src/BenchmarkDotNet/Reports/SummaryTableExtensions.cs +++ b/src/BenchmarkDotNet/Reports/SummaryTableExtensions.cs @@ -72,7 +72,7 @@ public static void PrintLine(this SummaryTable table, string[] line, ILogger log logger.WriteStatistic(text); } } - + if (startOfGroup && startOfGroupHighlightStrategy == MarkdownExporter.MarkdownHighlightStrategy.Marker) logger.Write(highlightRow ? LogKind.Header : LogKind.Statistic, " ^"); // diff --git a/src/BenchmarkDotNet/Running/BenchmarkConverter.cs b/src/BenchmarkDotNet/Running/BenchmarkConverter.cs index 98f8125f68..05d4928122 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkConverter.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkConverter.cs @@ -22,7 +22,7 @@ public static BenchmarkRunInfo TypeToBenchmarks(Type type, IConfig config = null // We should check all methods including private to notify users about private methods with the [Benchmark] attribute var bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; - + var fullConfig = GetFullConfig(type, config); var allMethods = type.GetMethods(bindingFlags); return MethodsToBenchmarksWithFullConfig(type, allMethods, fullConfig); @@ -90,11 +90,11 @@ public static ImmutableConfig GetFullConfig(Type type, IConfig config) var allAttributes = typeAttributes.Concat(assemblyAttributes); var configs = allAttributes.Select(attribute => attribute.Config) .OrderBy(c => c.GetJobs().Count(job => job.Meta.IsMutator)); // configs with mutators must be the ones applied at the end - + foreach (var configFromAttribute in configs) config = ManualConfig.Union(config, configFromAttribute); } - + return ImmutableConfigBuilder.Create(config); } @@ -239,7 +239,7 @@ private static string[] GetCategories(MethodInfo method) return attributes.SelectMany(attr => attr.Categories).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); } - private static ImmutableArray GetFilteredBenchmarks(IList benchmarks, IList filters) + private static ImmutableArray GetFilteredBenchmarks(IList benchmarks, IList filters) => benchmarks.Where(benchmark => filters.All(filter => filter.Predicate(benchmark))).ToImmutableArray(); private static void AssertMethodHasCorrectSignature(string methodType, MethodInfo methodInfo) diff --git a/src/BenchmarkDotNet/Running/BenchmarkId.cs b/src/BenchmarkDotNet/Running/BenchmarkId.cs index 938d0bba05..e01f284d13 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkId.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkId.cs @@ -18,7 +18,7 @@ public BenchmarkId(int value, BenchmarkCase benchmarkCase) } public int Value { get; } - + private string JobId { get; } private string FullBenchmarkName { get; } diff --git a/src/BenchmarkDotNet/Running/BenchmarkRunnerClean.cs b/src/BenchmarkDotNet/Running/BenchmarkRunnerClean.cs index b2dda53478..0876e9c939 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkRunnerClean.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkRunnerClean.cs @@ -28,14 +28,14 @@ namespace BenchmarkDotNet.Running internal static class BenchmarkRunnerClean { internal const string DateTimeFormat = "yyyyMMdd-HHmmss"; - + internal static readonly IResolver DefaultResolver = new CompositeResolver(EnvironmentResolver.Instance, InfrastructureResolver.Instance); internal static Summary[] Run(BenchmarkRunInfo[] benchmarkRunInfos) { var resolver = DefaultResolver; var artifactsToCleanup = new List(); - + var title = GetTitle(benchmarkRunInfos); var rootArtifactsFolderPath = GetRootArtifactsFolderPath(benchmarkRunInfos); var resultsFolderPath = GetResultsFolderPath(rootArtifactsFolderPath, benchmarkRunInfos); @@ -44,7 +44,7 @@ internal static Summary[] Run(BenchmarkRunInfo[] benchmarkRunInfos) using (var streamLogger = new StreamLogger(GetLogFileStreamWriter(benchmarkRunInfos, logFilePath))) { var compositeLogger = CreateCompositeLogger(benchmarkRunInfos, streamLogger); - + var supportedBenchmarks = GetSupportedBenchmarks(benchmarkRunInfos, compositeLogger, resolver); if (!supportedBenchmarks.Any(benchmarks => benchmarks.BenchmarksCases.Any())) return new [] { Summary.NothingToRun(title, resultsFolderPath, logFilePath) }; @@ -72,9 +72,9 @@ internal static Summary[] Run(BenchmarkRunInfo[] benchmarkRunInfos) foreach (var benchmarkRunInfo in supportedBenchmarks) // we run them in the old order now using the new build artifacts { var runChronometer = Chronometer.Start(); - + var summary = Run(benchmarkRunInfo, benchmarkToBuildResult, resolver, compositeLogger, artifactsToCleanup, resultsFolderPath, logFilePath, ref runChronometer); - + if (!benchmarkRunInfo.Config.Options.IsSet(ConfigOptions.JoinSummary)) PrintSummary(compositeLogger, benchmarkRunInfo.Config, summary); @@ -82,7 +82,7 @@ internal static Summary[] Run(BenchmarkRunInfo[] benchmarkRunInfos) compositeLogger.WriteLineHeader($"// ** Remained {benchmarksToRunCount} benchmark(s) to run **"); LogTotalTime(compositeLogger, runChronometer.GetElapsed().GetTimeSpan(), summary.GetNumberOfExecutedBenchmarks(), message: "Run time"); compositeLogger.WriteLine(); - + results.Add(summary); if (benchmarkRunInfo.Config.Options.IsSet(ConfigOptions.StopOnFirstError) && summary.Reports.Any(report => !report.Success)) @@ -92,13 +92,13 @@ internal static Summary[] Run(BenchmarkRunInfo[] benchmarkRunInfos) if (supportedBenchmarks.Any(b => b.Config.Options.IsSet(ConfigOptions.JoinSummary))) { var joinedSummary = Summary.Join(results, globalChronometer.GetElapsed()); - + PrintSummary(compositeLogger, supportedBenchmarks.First(b => b.Config.Options.IsSet(ConfigOptions.JoinSummary)).Config, joinedSummary); - + results.Clear(); results.Add(joinedSummary); } - + var totalTime = globalChronometer.GetElapsed().GetTimeSpan(); int totalNumberOfExecutedBenchmarks = results.Sum(summary => summary.GetNumberOfExecutedBenchmarks()); LogTotalTime(compositeLogger, totalTime, totalNumberOfExecutedBenchmarks, "Global total time"); @@ -114,11 +114,11 @@ internal static Summary[] Run(BenchmarkRunInfo[] benchmarkRunInfos) } } - private static Summary Run(BenchmarkRunInfo benchmarkRunInfo, - Dictionary buildResults, + private static Summary Run(BenchmarkRunInfo benchmarkRunInfo, + Dictionary buildResults, IResolver resolver, - ILogger logger, - List artifactsToCleanup, + ILogger logger, + List artifactsToCleanup, string resultsFolderPath, string logFilePath, ref StartedClock runChronometer) @@ -175,7 +175,7 @@ private static Summary Run(BenchmarkRunInfo benchmarkRunInfo, logger.WriteLine(); } } - + var clockSpan = runChronometer.GetElapsed(); return new Summary(title, @@ -183,7 +183,7 @@ private static Summary Run(BenchmarkRunInfo benchmarkRunInfo, HostEnvironmentInfo.GetCurrent(), resultsFolderPath, logFilePath, - clockSpan.GetTimeSpan(), + clockSpan.GetTimeSpan(), Validate(new[] {benchmarkRunInfo }, NullLogger.Instance)); // validate them once again, but don't print the output } @@ -553,7 +553,7 @@ private static ILogger CreateCompositeLogger(BenchmarkRunInfo[] benchmarkRunInfo builder.Add(logger); builder.Add(streamLogger); - + return new CompositeLogger(builder.ToImmutable()); } diff --git a/src/BenchmarkDotNet/Running/BenchmarkRunnerDirty.cs b/src/BenchmarkDotNet/Running/BenchmarkRunnerDirty.cs index 10f68a28ed..122dc5b835 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkRunnerDirty.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkRunnerDirty.cs @@ -11,7 +11,7 @@ namespace BenchmarkDotNet.Running { - // VS generates bad assembly binding redirects for ValueTuple for Full .NET Framework + // VS generates bad assembly binding redirects for ValueTuple for Full .NET Framework // we need to keep the logic that uses it in a separate method and create DirtyAssemblyResolveHelper first // so it can ignore the version mismatch ;) public static class BenchmarkRunner diff --git a/src/BenchmarkDotNet/Running/BenchmarkSwitcher.cs b/src/BenchmarkDotNet/Running/BenchmarkSwitcher.cs index 1da8553e0f..daf9408e42 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkSwitcher.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkSwitcher.cs @@ -55,7 +55,7 @@ public class BenchmarkSwitcher [PublicAPI] public IEnumerable Run(string[] args = null, IConfig config = null) { - // VS generates bad assembly binding redirects for ValueTuple for Full .NET Framework + // VS generates bad assembly binding redirects for ValueTuple for Full .NET Framework // we need to keep the logic that uses it in a separate method and create DirtyAssemblyResolveHelper first // so it can ignore the version mismatch ;) using (DirtyAssemblyResolveHelper.Create()) diff --git a/src/BenchmarkDotNet/Running/Descriptor.cs b/src/BenchmarkDotNet/Running/Descriptor.cs index bbf7e3bfbd..85fb3e3068 100644 --- a/src/BenchmarkDotNet/Running/Descriptor.cs +++ b/src/BenchmarkDotNet/Running/Descriptor.cs @@ -31,7 +31,7 @@ public class Descriptor public Descriptor( Type type, - MethodInfo workloadMethod, + MethodInfo workloadMethod, MethodInfo globalSetupMethod = null, MethodInfo globalCleanupMethod = null, MethodInfo iterationSetupMethod = null, diff --git a/src/BenchmarkDotNet/Running/IUserInteraction.cs b/src/BenchmarkDotNet/Running/IUserInteraction.cs index 59796bc41c..e4210690c2 100644 --- a/src/BenchmarkDotNet/Running/IUserInteraction.cs +++ b/src/BenchmarkDotNet/Running/IUserInteraction.cs @@ -4,10 +4,10 @@ namespace BenchmarkDotNet.Running { - internal interface IUserInteraction + internal interface IUserInteraction { void PrintNoBenchmarksError(ILogger logger); - + void PrintWrongFilterInfo(IReadOnlyList allTypes, ILogger logger, string[] userFilters); IReadOnlyList AskUser(IReadOnlyList allTypes, ILogger logger); diff --git a/src/BenchmarkDotNet/Running/TypeFilter.cs b/src/BenchmarkDotNet/Running/TypeFilter.cs index c2fa515202..c295833016 100644 --- a/src/BenchmarkDotNet/Running/TypeFilter.cs +++ b/src/BenchmarkDotNet/Running/TypeFilter.cs @@ -14,7 +14,7 @@ internal static class TypeFilter internal static (bool allTypesValid, IReadOnlyList runnable) GetTypesWithRunnableBenchmarks(IEnumerable types, IEnumerable assemblies, ILogger logger) { var validRunnableTypes = new List(); - + foreach (var type in types) { if (type.ContainsRunnableBenchmarks()) @@ -24,7 +24,7 @@ internal static (bool allTypesValid, IReadOnlyList runnable) GetTypesWithR else { logger.WriteLineError($"Type {type} is invalid. Only public, non-generic (closed generic types with public parameterless ctors are supported), non-abstract, non-sealed, non-static types with public instance [Benchmark] method(s) are supported."); - + return (false, Array.Empty()); } } diff --git a/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchain.cs b/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchain.cs index c206d84fee..1aa00f21bc 100644 --- a/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchain.cs +++ b/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchain.cs @@ -32,7 +32,7 @@ public class CoreRtToolchain : Toolchain /// public static readonly IToolchain Core50 = CreateBuilder().UseCoreRtNuGet().TargetFrameworkMoniker("netcoreapp5.0").ToToolchain(); - internal CoreRtToolchain(string displayName, + internal CoreRtToolchain(string displayName, string coreRtVersion, string ilcPath, bool useCppCodeGenerator, string runtimeFrameworkVersion, string targetFrameworkMoniker, string runtimeIdentifier, string customDotNetCliPath, string packagesRestorePath, @@ -40,10 +40,10 @@ internal CoreRtToolchain(string displayName, TimeSpan timeout, bool rootAllApplicationAssemblies, bool ilcGenerateCompleteTypeMetadata, bool ilcGenerateStackTraceData) : base(displayName, - new Generator(coreRtVersion, useCppCodeGenerator, runtimeFrameworkVersion, targetFrameworkMoniker, customDotNetCliPath, + new Generator(coreRtVersion, useCppCodeGenerator, runtimeFrameworkVersion, targetFrameworkMoniker, customDotNetCliPath, runtimeIdentifier, feeds, useNuGetClearTag, useTempFolderForRestore, packagesRestorePath, rootAllApplicationAssemblies, ilcGenerateCompleteTypeMetadata, ilcGenerateStackTraceData), - new DotNetCliPublisher(customDotNetCliPath, GetExtraArguments(useCppCodeGenerator, runtimeIdentifier), GetEnvironmentVariables(ilcPath), timeout), + new DotNetCliPublisher(customDotNetCliPath, GetExtraArguments(useCppCodeGenerator, runtimeIdentifier), GetEnvironmentVariables(ilcPath), timeout), new Executor()) { IlcPath = ilcPath; @@ -52,10 +52,10 @@ internal CoreRtToolchain(string displayName, public string IlcPath { get; } public static CoreRtToolchainBuilder CreateBuilder() => CoreRtToolchainBuilder.Create(); - + private static string GetExtraArguments(bool useCppCodeGenerator, string runtimeIdentifier) => useCppCodeGenerator ? $"-r {runtimeIdentifier} /p:NativeCodeGen=cpp" : $"-r {runtimeIdentifier}"; - + // https://github.com/dotnet/corert/blob/7f902d4d8b1c3280e60f5e06c71951a60da173fb/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md#compiling-source-to-native-code-using-the-ilcompiler-you-built // we have to pass IlcPath env var to get it working private static IReadOnlyList GetEnvironmentVariables(string ilcPath) diff --git a/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchainBuilder.cs b/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchainBuilder.cs index 772a8d6ad8..4648382d91 100644 --- a/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchainBuilder.cs +++ b/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchainBuilder.cs @@ -59,7 +59,7 @@ public CoreRtToolchainBuilder UseCoreRtLocal(string newIlcPath) } /// - /// "This approach uses transpiler to convert IL to C++, and then uses platform specific C++ compiler and linker for compiling/linking the application. + /// "This approach uses transpiler to convert IL to C++, and then uses platform specific C++ compiler and linker for compiling/linking the application. /// The transpiler is a lot less mature than the RyuJIT path. If you came here to give CoreRT a try" please don't use this option. /// Based on https://github.com/dotnet/corert/blob/7f902d4d8b1c3280e60f5e06c71951a60da173fb/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md#using-cpp-code-generator /// diff --git a/src/BenchmarkDotNet/Toolchains/CoreRt/Generator.cs b/src/BenchmarkDotNet/Toolchains/CoreRt/Generator.cs index f95e74a1f7..a3833ae37a 100644 --- a/src/BenchmarkDotNet/Toolchains/CoreRt/Generator.cs +++ b/src/BenchmarkDotNet/Toolchains/CoreRt/Generator.cs @@ -13,7 +13,7 @@ namespace BenchmarkDotNet.Toolchains.CoreRt { /// /// generates new csproj file for self-contained .NET Core RT app - /// based on https://github.com/dotnet/corert/blob/7f902d4d8b1c3280e60f5e06c71951a60da173fb/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md#compiling-source-to-native-code-using-the-ilcompiler-you-built + /// based on https://github.com/dotnet/corert/blob/7f902d4d8b1c3280e60f5e06c71951a60da173fb/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md#compiling-source-to-native-code-using-the-ilcompiler-you-built /// and https://github.com/dotnet/corert/tree/7f902d4d8b1c3280e60f5e06c71951a60da173fb/samples/HelloWorld#add-corert-to-your-project /// public class Generator : CsProjGenerator @@ -22,7 +22,7 @@ public class Generator : CsProjGenerator internal Generator(string coreRtVersion, bool useCppCodeGenerator, string runtimeFrameworkVersion, string targetFrameworkMoniker, string cliPath, - string runtimeIdentifier, IReadOnlyDictionary feeds, bool useNuGetClearTag, + string runtimeIdentifier, IReadOnlyDictionary feeds, bool useNuGetClearTag, bool useTempFolderForRestore, string packagesRestorePath, bool rootAllApplicationAssemblies, bool ilcGenerateCompleteTypeMetadata, bool ilcGenerateStackTraceData) : base(targetFrameworkMoniker, cliPath, GetPackagesDirectoryPath(useTempFolderForRestore, packagesRestorePath), runtimeFrameworkVersion) @@ -71,11 +71,11 @@ protected override void GenerateBuildScript(BuildPartition buildPartition, Artif .AppendLine($"call {CliPath ?? "dotnet"} {DotNetCliCommand.GetBuildCommand(artifactsPaths, buildPartition)} {extraArguments}") .AppendLine($"call {CliPath ?? "dotnet"} {DotNetCliCommand.GetPublishCommand(artifactsPaths, buildPartition)} {extraArguments}") .ToString(); - + File.WriteAllText(artifactsPaths.BuildScriptFilePath, content); } - // we always want to have a new directory for NuGet packages restore + // we always want to have a new directory for NuGet packages restore // to avoid this https://github.com/dotnet/coreclr/blob/master/Documentation/workflow/UsingDotNetCli.md#update-coreclr-using-runtime-nuget-package // some of the packages are going to contain source code, so they can not be in the subfolder of current solution // otherwise they would be compiled too (new .csproj include all .cs files from subfolders by default diff --git a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunGenerator.cs b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunGenerator.cs index 2bcad22e6b..c988066f79 100644 --- a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunGenerator.cs +++ b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunGenerator.cs @@ -14,7 +14,7 @@ public CoreRunGenerator(FileInfo sourceCoreRun, FileInfo copyCoreRun, string tar } private FileInfo SourceCoreRun { get; } - + private FileInfo CopyCoreRun { get; } private bool NeedsCopy => SourceCoreRun != CopyCoreRun; @@ -29,21 +29,21 @@ protected override void CopyAllRequiredFiles(ArtifactsPaths artifactsPaths) { if (NeedsCopy) CopyFilesRecursively(SourceCoreRun.Directory, CopyCoreRun.Directory); - + base.CopyAllRequiredFiles(artifactsPaths); } - protected override string[] GetArtifactsToCleanup(ArtifactsPaths artifactsPaths) - => NeedsCopy - ? base.GetArtifactsToCleanup(artifactsPaths).Concat(new [] { CopyCoreRun.Directory.FullName }).ToArray() + protected override string[] GetArtifactsToCleanup(ArtifactsPaths artifactsPaths) + => NeedsCopy + ? base.GetArtifactsToCleanup(artifactsPaths).Concat(new [] { CopyCoreRun.Directory.FullName }).ToArray() : base.GetArtifactsToCleanup(artifactsPaths); // source: https://stackoverflow.com/a/58779/5852046 - private static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) + private static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) { if (!target.Exists) target.Create(); - + foreach (DirectoryInfo dir in source.GetDirectories()) CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name)); diff --git a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunPublisher.cs b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunPublisher.cs index 62d80a4483..9fbbb7de3e 100644 --- a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunPublisher.cs +++ b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunPublisher.cs @@ -30,7 +30,7 @@ public BuildResult Build(GenerateResult generateResult, BuildPartition buildPart return buildResult; } - + /// /// update CoreRun folder with newer versions of duplicated dependencies /// @@ -44,20 +44,20 @@ private void UpdateDuplicatedDependencies(ArtifactsPaths artifactsPaths, ILogger .Where(file => file.Extension == ".dll" || file.Extension == ".exe" )) { var coreRunDependency = new FileInfo(Path.Combine(coreRunDirectory.FullName, publishedDependency.Name)); - + if (!coreRunDependency.Exists) continue; // the file does not exist in CoreRun directory, we don't need to worry, it will be just loaded from publish directory by CoreRun var publishedVersionInfo = FileVersionInfo.GetVersionInfo(publishedDependency.FullName); var coreRunVersionInfo = FileVersionInfo.GetVersionInfo(coreRunDependency.FullName); - + if(!Version.TryParse(publishedVersionInfo.FileVersion, out var publishedVersion) || !Version.TryParse(coreRunVersionInfo.FileVersion, out var coreRunVersion)) continue; - - if(publishedVersion > coreRunVersion) + + if(publishedVersion > coreRunVersion) { File.Copy(publishedDependency.FullName, coreRunDependency.FullName, overwrite: true); // we need to overwrite old things with their newer versions - + logger.WriteLineInfo($"Copying {publishedDependency.FullName} to {coreRunDependency.FullName}"); } } diff --git a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunToolchain.cs b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunToolchain.cs index 9700ea76dd..14d9ea42dd 100644 --- a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunToolchain.cs +++ b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunToolchain.cs @@ -20,10 +20,10 @@ public class CoreRunToolchain : IToolchain /// the directory to restore packages to /// the timeout for building the benchmarks public CoreRunToolchain(FileInfo coreRun, bool createCopy = true, - string targetFrameworkMoniker = "netcoreapp2.1", + string targetFrameworkMoniker = "netcoreapp2.1", FileInfo customDotNetCliPath = null, DirectoryInfo restorePath = null, string displayName = "CoreRun", - TimeSpan? timeout = null) + TimeSpan? timeout = null) { if (coreRun == null) throw new ArgumentNullException(nameof(coreRun)); if (!coreRun.Exists) throw new FileNotFoundException("Provided CoreRun path does not exist. Please remember that BDN expects path to CoreRun.exe (corerun on Unix), not to Core_Root folder."); @@ -36,15 +36,15 @@ public CoreRunToolchain(FileInfo coreRun, bool createCopy = true, Name = displayName; Generator = new CoreRunGenerator(SourceCoreRun, CopyCoreRun, targetFrameworkMoniker, customDotNetCliPath?.FullName, restorePath?.FullName); Builder = new CoreRunPublisher(CopyCoreRun, customDotNetCliPath, timeout); - Executor = new DotNetCliExecutor(customDotNetCliPath: CopyCoreRun.FullName); // instead of executing "dotnet $pathToDll" we do "CoreRun $pathToDll" + Executor = new DotNetCliExecutor(customDotNetCliPath: CopyCoreRun.FullName); // instead of executing "dotnet $pathToDll" we do "CoreRun $pathToDll" } public string Name { get; } - + public IGenerator Generator { get; } - + public IBuilder Builder { get; } - + public IExecutor Executor { get; } public bool IsInProcess => false; @@ -54,7 +54,7 @@ public CoreRunToolchain(FileInfo coreRun, bool createCopy = true, public FileInfo CopyCoreRun { get; } public FileInfo CustomDotNetCliPath { get; } - + public DirectoryInfo RestorePath { get; } public override string ToString() => Name; @@ -66,7 +66,7 @@ public bool IsSupported(BenchmarkCase benchmark, ILogger logger, IResolver resol logger.WriteLineError($"Provided CoreRun path does not exist, benchmark '{benchmark.DisplayInfo}' will not be executed. Please remember that BDN expects path to CoreRun.exe (corerun on Unix), not to Core_Root folder."); return false; } - + if (Toolchain.InvalidCliPath(CustomDotNetCliPath?.FullName, benchmark, logger)) return false; diff --git a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjCoreToolchain.cs b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjCoreToolchain.cs index b48d3cd1ec..300697c5c8 100644 --- a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjCoreToolchain.cs +++ b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjCoreToolchain.cs @@ -20,7 +20,7 @@ public class CsProjCoreToolchain : Toolchain [PublicAPI] public static readonly IToolchain NetCoreApp31 = From(NetCoreAppSettings.NetCoreApp31); [PublicAPI] public static readonly IToolchain NetCoreApp50 = From(NetCoreAppSettings.NetCoreApp50); - private CsProjCoreToolchain(string name, IGenerator generator, IBuilder builder, IExecutor executor, string customDotNetCliPath) + private CsProjCoreToolchain(string name, IGenerator generator, IBuilder builder, IExecutor executor, string customDotNetCliPath) : base(name, generator, builder, executor) { CustomDotNetCliPath = customDotNetCliPath; @@ -31,8 +31,8 @@ private CsProjCoreToolchain(string name, IGenerator generator, IBuilder builder, [PublicAPI] public static IToolchain From(NetCoreAppSettings settings) => new CsProjCoreToolchain(settings.Name, - new CsProjGenerator(settings.TargetFrameworkMoniker, settings.CustomDotNetCliPath, settings.PackagesPath, settings.RuntimeFrameworkVersion), - new DotNetCliBuilder(settings.TargetFrameworkMoniker, settings.CustomDotNetCliPath, settings.Timeout), + new CsProjGenerator(settings.TargetFrameworkMoniker, settings.CustomDotNetCliPath, settings.PackagesPath, settings.RuntimeFrameworkVersion), + new DotNetCliBuilder(settings.TargetFrameworkMoniker, settings.CustomDotNetCliPath, settings.Timeout), new DotNetCliExecutor(settings.CustomDotNetCliPath), settings.CustomDotNetCliPath); diff --git a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs index d44f6df1ac..415cc9f78f 100644 --- a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs +++ b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs @@ -126,7 +126,7 @@ protected virtual string GetRuntimeSettings(GcMode gcMode, IResolver resolver) // custom SDKs are not added for non-netcoreapp apps (like net471), so when the TFM != netcoreapp we dont parse " - if (trimmedLine.StartsWith(" private const string MandatoryMsBuildSettings = " /p:UseSharedCompilation=false /p:BuildInParallel=false /m:1"; - + [PublicAPI] public string CliPath { get; } - + [PublicAPI] public string Arguments { get; } [PublicAPI] public GenerateResult GenerateResult { get; } @@ -30,10 +30,10 @@ public class DotNetCliCommand [PublicAPI] public BuildPartition BuildPartition { get; } [PublicAPI] public IReadOnlyList EnvironmentVariables { get; } - + [PublicAPI] public TimeSpan Timeout { get; } - public DotNetCliCommand(string cliPath, string arguments, GenerateResult generateResult, ILogger logger, + public DotNetCliCommand(string cliPath, string arguments, GenerateResult generateResult, ILogger logger, BuildPartition buildPartition, IReadOnlyList environmentVariables, TimeSpan timeout) { CliPath = cliPath; @@ -44,7 +44,7 @@ public DotNetCliCommand(string cliPath, string arguments, GenerateResult generat EnvironmentVariables = environmentVariables; Timeout = timeout; } - + public DotNetCliCommand WithArguments(string arguments) => new DotNetCliCommand(CliPath, arguments, GenerateResult, Logger, BuildPartition, EnvironmentVariables, Timeout); @@ -140,7 +140,7 @@ public DotNetCliCommandResult PublishNoBuildAndNoRestore() internal static IEnumerable GetAddPackagesCommands(BuildPartition buildPartition) => GetNuGetAddPackageCommands(buildPartition.RepresentativeBenchmarkCase, buildPartition.Resolver); - internal static string GetRestoreCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string extraArguments = null) + internal static string GetRestoreCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string extraArguments = null) => new StringBuilder() .Append("restore ") .Append(string.IsNullOrEmpty(artifactsPaths.PackagesDirectoryName) ? string.Empty : $"--packages \"{artifactsPaths.PackagesDirectoryName}\" ") @@ -148,8 +148,8 @@ internal static string GetRestoreCommand(ArtifactsPaths artifactsPaths, BuildPar .Append(extraArguments) .Append(MandatoryMsBuildSettings) .ToString(); - - internal static string GetBuildCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string extraArguments = null) + + internal static string GetBuildCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string extraArguments = null) => new StringBuilder() .Append($"build -c {buildPartition.BuildConfiguration} ") // we don't need to specify TFM, our auto-generated project contains always single one .Append(GetCustomMsBuildArguments(buildPartition.RepresentativeBenchmarkCase, buildPartition.Resolver)) @@ -157,8 +157,8 @@ internal static string GetBuildCommand(ArtifactsPaths artifactsPaths, BuildParti .Append(MandatoryMsBuildSettings) .Append(string.IsNullOrEmpty(artifactsPaths.PackagesDirectoryName) ? string.Empty : $" /p:NuGetPackageRoot=\"{artifactsPaths.PackagesDirectoryName}\"") .ToString(); - - internal static string GetPublishCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string extraArguments = null) + + internal static string GetPublishCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string extraArguments = null) => new StringBuilder() .Append($"publish -c {buildPartition.BuildConfiguration} ") // we don't need to specify TFM, our auto-generated project contains always single one .Append(GetCustomMsBuildArguments(buildPartition.RepresentativeBenchmarkCase, buildPartition.Resolver)) diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs index 449eec2c5e..6d7caab82a 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs @@ -49,7 +49,7 @@ public static DotNetCliCommandResult Execute(DotNetCliCommand parameters) : DotNetCliCommandResult.Failure(stopwatch.Elapsed, outputReader.GetOutputText(), outputReader.GetErrorText()); } } - + internal static string GetDotNetSdkVersion() { using (var process = new Process { StartInfo = BuildStartInfo(customDotNetCliPath: null, workingDirectory: string.Empty, arguments: "--version") }) diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandResult.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandResult.cs index 4597cc6325..3d65270621 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandResult.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandResult.cs @@ -3,7 +3,7 @@ using BenchmarkDotNet.Toolchains.Results; using JetBrains.Annotations; -namespace BenchmarkDotNet.Toolchains.DotNetCli +namespace BenchmarkDotNet.Toolchains.DotNetCli { public struct DotNetCliCommandResult { diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliExecutor.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliExecutor.cs index 80d6bd5c1a..32aed0645f 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliExecutor.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliExecutor.cs @@ -30,7 +30,7 @@ public ExecuteResult Execute(ExecuteParameters executeParameters) executeParameters.Logger.WriteLineError($"Did not find {executeParameters.BuildResult.ArtifactsPaths.ExecutablePath}, but the folder contained:"); foreach (var file in new DirectoryInfo(executeParameters.BuildResult.ArtifactsPaths.BinariesDirectoryPath).GetFiles("*.*")) executeParameters.Logger.WriteLineError(file.Name); - + return new ExecuteResult(false, -1, default, Array.Empty(), Array.Empty()); } @@ -39,16 +39,16 @@ public ExecuteResult Execute(ExecuteParameters executeParameters) return Execute( executeParameters.BenchmarkCase, executeParameters.BenchmarkId, - executeParameters.Logger, - executeParameters.BuildResult.ArtifactsPaths, - executeParameters.Diagnoser, - Path.GetFileName(executeParameters.BuildResult.ArtifactsPaths.ExecutablePath), + executeParameters.Logger, + executeParameters.BuildResult.ArtifactsPaths, + executeParameters.Diagnoser, + Path.GetFileName(executeParameters.BuildResult.ArtifactsPaths.ExecutablePath), executeParameters.Resolver); } finally { executeParameters.Diagnoser?.Handle( - HostSignal.AfterProcessExit, + HostSignal.AfterProcessExit, new DiagnoserActionParameters(null, executeParameters.BenchmarkCase, executeParameters.BenchmarkId)); } } diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliGenerator.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliGenerator.cs index 271dde431b..07d40d4bb7 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliGenerator.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliGenerator.cs @@ -37,7 +37,7 @@ protected override string GetBuildArtifactsDirectoryPath(BuildPartition buildPar return Path.Combine(directoryInfo.FullName, programName); } - // we did not find global.json or any Visual Studio solution file? + // we did not find global.json or any Visual Studio solution file? // let's return it in the old way and hope that it works ;) var parent = new DirectoryInfo(Directory.GetCurrentDirectory()).Parent; if (parent == null) @@ -87,6 +87,6 @@ protected override void GenerateBuildScript(BuildPartition buildPartition, Artif private static bool IsRootSolutionFolder(DirectoryInfo directoryInfo) => directoryInfo .GetFileSystemInfos() - .Any(fileInfo => fileInfo.Extension == ".sln" || fileInfo.Name == "global.json"); + .Any(fileInfo => fileInfo.Extension == ".sln" || fileInfo.Name == "global.json"); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs index f9a11696f2..a4b01237e6 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs @@ -25,12 +25,12 @@ public DotNetCliPublisher(string customDotNetCliPath = null, string extraArgumen private TimeSpan Timeout { get; } - public BuildResult Build(GenerateResult generateResult, BuildPartition buildPartition, ILogger logger) + public BuildResult Build(GenerateResult generateResult, BuildPartition buildPartition, ILogger logger) => new DotNetCliCommand( - CustomDotNetCliPath, - ExtraArguments, - generateResult, - logger, + CustomDotNetCliPath, + ExtraArguments, + generateResult, + logger, buildPartition, EnvironmentVariables, Timeout) diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/MsBuildErrorMapper.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/MsBuildErrorMapper.cs index 283f77e939..4e9a1f4060 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/MsBuildErrorMapper.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/MsBuildErrorMapper.cs @@ -17,7 +17,7 @@ internal static class MsBuildErrorMapper $"Example: {Map(match.Groups[2])};{Map(match.Groups[3])}" ), ( - new Regex("error NU1201: Project (.*) is not compatible with (.*) ((.*)) / (.*). Project (.*) supports: (.*) ((.*))", + new Regex("error NU1201: Project (.*) is not compatible with (.*) ((.*)) / (.*). Project (.*) supports: (.*) ((.*))", RegexOptions.CultureInvariant | RegexOptions.Compiled), match => $@"The project which defines benchmarks does not target '{Map(match.Groups[2])}'." + Environment.NewLine + $"You need to add '{Map(match.Groups[2])}' to in your project file ('{match.Groups[1]}')." + Environment.NewLine + diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs index c56c8eaee0..e936d9bcb4 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs @@ -38,8 +38,8 @@ public class NetCoreAppSettings /// [PublicAPI] public NetCoreAppSettings( - string targetFrameworkMoniker, - string runtimeFrameworkVersion, + string targetFrameworkMoniker, + string runtimeFrameworkVersion, string name, string customDotNetCliPath = null, string packagesPath = null, @@ -66,7 +66,7 @@ public NetCoreAppSettings( public string Name { get; } public string CustomDotNetCliPath { get; } - + /// /// The directory to restore packages to. /// @@ -79,10 +79,10 @@ public NetCoreAppSettings( public NetCoreAppSettings WithCustomDotNetCliPath(string customDotNetCliPath, string displayName = null) => new NetCoreAppSettings(TargetFrameworkMoniker, RuntimeFrameworkVersion, displayName ?? Name, customDotNetCliPath, PackagesPath, Timeout); - + public NetCoreAppSettings WithCustomPackagesRestorePath(string packagesPath, string displayName = null) => new NetCoreAppSettings(TargetFrameworkMoniker, RuntimeFrameworkVersion, displayName ?? Name, CustomDotNetCliPath, packagesPath, Timeout); - + public NetCoreAppSettings WithTimeout(TimeSpan? timeOut) => new NetCoreAppSettings(TargetFrameworkMoniker, RuntimeFrameworkVersion, Name, CustomDotNetCliPath, PackagesPath, timeOut ?? Timeout); diff --git a/src/BenchmarkDotNet/Toolchains/GeneratorBase.cs b/src/BenchmarkDotNet/Toolchains/GeneratorBase.cs index 4458e1d625..7300edfacb 100644 --- a/src/BenchmarkDotNet/Toolchains/GeneratorBase.cs +++ b/src/BenchmarkDotNet/Toolchains/GeneratorBase.cs @@ -108,7 +108,7 @@ [PublicAPI] protected virtual void GenerateAppConfig(BuildPartition buildPartiti /// generates the C# source code with all required boilerplate. /// You most probably do NOT need to override this method!! /// - [PublicAPI] protected virtual void GenerateCode(BuildPartition buildPartition, ArtifactsPaths artifactsPaths) + [PublicAPI] protected virtual void GenerateCode(BuildPartition buildPartition, ArtifactsPaths artifactsPaths) => File.WriteAllText(artifactsPaths.ProgramCodePath, CodeGenerator.Generate(buildPartition)); private ArtifactsPaths GetArtifactsPaths(BuildPartition buildPartition, string rootArtifactsFolderPath) diff --git a/src/BenchmarkDotNet/Toolchains/InProcess.Emit.Implementation/Emitters/NonConsumableConsumeEmitter.cs b/src/BenchmarkDotNet/Toolchains/InProcess.Emit.Implementation/Emitters/NonConsumableConsumeEmitter.cs index 7e3ce151f9..4087165f3b 100644 --- a/src/BenchmarkDotNet/Toolchains/InProcess.Emit.Implementation/Emitters/NonConsumableConsumeEmitter.cs +++ b/src/BenchmarkDotNet/Toolchains/InProcess.Emit.Implementation/Emitters/NonConsumableConsumeEmitter.cs @@ -50,7 +50,7 @@ private MethodBuilder EmitNonGenericKeepAliveWithoutBoxing(string methodName, Ty method private hidebysig instance void NonGenericKeepAliveWithoutBoxing( valuetype BenchmarkDotNet.Samples.CustomStructNonConsumable _ - ) cil managed noinlining + ) cil managed noinlining */ var valueArg = new EmitParameterInfo( 0, diff --git a/src/BenchmarkDotNet/Toolchains/InProcess.Emit.Implementation/Emitters/RunnableEmitter.cs b/src/BenchmarkDotNet/Toolchains/InProcess.Emit.Implementation/Emitters/RunnableEmitter.cs index 84b75a54c9..91e97cc71e 100644 --- a/src/BenchmarkDotNet/Toolchains/InProcess.Emit.Implementation/Emitters/RunnableEmitter.cs +++ b/src/BenchmarkDotNet/Toolchains/InProcess.Emit.Implementation/Emitters/RunnableEmitter.cs @@ -476,14 +476,14 @@ private void DefineFields() private ConstructorBuilder DefineCtor() { - // .method public hidebysig specialname rtspecialname + // .method public hidebysig specialname rtspecialname // instance void.ctor() cil managed return runnableBuilder.DefinePublicInstanceCtor(); } private MethodBuilder DefineTrickTheJitMethod() { - // .method public hidebysig + // .method public hidebysig // instance void __TrickTheJIT__() cil managed noinlining nooptimization var result = runnableBuilder .DefinePublicNonVirtualVoidInstanceMethod(TrickTheJitCoreMethodName) @@ -541,7 +541,7 @@ private MethodBuilder EmitOverheadImplementation(string methodName) { var overheadInvokeMethod = TypeBuilderExtensions.GetDelegateInvokeMethod(overheadDelegateType); - //.method private hidebysig + //.method private hidebysig // instance int32 __Overhead(int64 arg0) cil managed var methodBuilder = runnableBuilder.DefineNonVirtualInstanceMethod( methodName, @@ -572,7 +572,7 @@ private MethodInfo EmitWorkloadImplementation(string methodName) var workloadInvokeMethod = TypeBuilderExtensions.GetDelegateInvokeMethod(workloadDelegateType); - //.method private hidebysig + //.method private hidebysig // instance int32 __Workload(int64 arg0) cil managed var args = workloadInvokeMethod.GetParameters(); var methodBuilder = runnableBuilder.DefineNonVirtualInstanceMethod( @@ -655,7 +655,7 @@ private MethodBuilder EmitActionImpl(string methodName, RunnableActionKind actio } // .method private hidebysig - // instance void OverheadActionUnroll(int64 invokeCount) cil managed + // instance void OverheadActionUnroll(int64 invokeCount) cil managed var toArg = new EmitParameterInfo(0, InvokeCountParamName, typeof(long)); var actionMethodBuilder = runnableBuilder.DefineNonVirtualInstanceMethod( methodName, @@ -808,7 +808,7 @@ private void EmitLoadArgFieldsToLocals(ILGenerator ilBuilder, IReadOnlyList(); /* - .method public hidebysig static + .method public hidebysig static void Run ( class [BenchmarkDotNet]BenchmarkDotNet.Running.BenchmarkCase benchmarkCase, class [BenchmarkDotNet]BenchmarkDotNet.Engines.IHost host diff --git a/src/BenchmarkDotNet/Toolchains/Results/BuildResult.cs b/src/BenchmarkDotNet/Toolchains/Results/BuildResult.cs index 43c1621232..cf2b5729e5 100644 --- a/src/BenchmarkDotNet/Toolchains/Results/BuildResult.cs +++ b/src/BenchmarkDotNet/Toolchains/Results/BuildResult.cs @@ -22,7 +22,7 @@ public static BuildResult Success(GenerateResult generateResult) => new BuildResult(generateResult, true, null); [PublicAPI] - public static BuildResult Failure(GenerateResult generateResult, string errorMessage) + public static BuildResult Failure(GenerateResult generateResult, string errorMessage) => new BuildResult(generateResult, false, errorMessage); [PublicAPI] diff --git a/src/BenchmarkDotNet/Toolchains/Results/GenerateResult.cs b/src/BenchmarkDotNet/Toolchains/Results/GenerateResult.cs index fa5b50cd35..8222e5c491 100644 --- a/src/BenchmarkDotNet/Toolchains/Results/GenerateResult.cs +++ b/src/BenchmarkDotNet/Toolchains/Results/GenerateResult.cs @@ -18,10 +18,10 @@ public GenerateResult(ArtifactsPaths artifactsPaths, bool isGenerateSuccess, Exc ArtifactsToCleanup = artifactsToCleanup; } - public static GenerateResult Success(ArtifactsPaths artifactsPaths, IReadOnlyCollection artifactsToCleanup) + public static GenerateResult Success(ArtifactsPaths artifactsPaths, IReadOnlyCollection artifactsToCleanup) => new GenerateResult(artifactsPaths, true, null, artifactsToCleanup); - public static GenerateResult Failure(ArtifactsPaths artifactsPaths, IReadOnlyCollection artifactsToCleanup, Exception exception = null) + public static GenerateResult Failure(ArtifactsPaths artifactsPaths, IReadOnlyCollection artifactsToCleanup, Exception exception = null) => new GenerateResult(artifactsPaths, false, exception, artifactsToCleanup); public override string ToString() => "GenerateResult: " + (IsGenerateSuccess ? "Success" : "Fail"); diff --git a/src/BenchmarkDotNet/Toolchains/Roslyn/Generator.cs b/src/BenchmarkDotNet/Toolchains/Roslyn/Generator.cs index cbdb9046f1..c3082d09bd 100644 --- a/src/BenchmarkDotNet/Toolchains/Roslyn/Generator.cs +++ b/src/BenchmarkDotNet/Toolchains/Roslyn/Generator.cs @@ -12,12 +12,12 @@ namespace BenchmarkDotNet.Toolchains.Roslyn [PublicAPI] public class Generator : GeneratorBase { - protected override string GetBuildArtifactsDirectoryPath(BuildPartition buildPartition, string programName) + protected override string GetBuildArtifactsDirectoryPath(BuildPartition buildPartition, string programName) => Path.GetDirectoryName(buildPartition.AssemblyLocation); [PublicAPI] protected override string[] GetArtifactsToCleanup(ArtifactsPaths artifactsPaths) - => new[] + => new[] { artifactsPaths.ProgramCodePath, artifactsPaths.AppConfigPath, @@ -47,7 +47,7 @@ protected override void GenerateBuildScript(BuildPartition buildPartition, Artif prefix + string.Join(" ", list)); } - internal static IEnumerable GetAllReferences(BenchmarkCase benchmarkCase) + internal static IEnumerable GetAllReferences(BenchmarkCase benchmarkCase) => benchmarkCase.Descriptor.Type.GetTypeInfo().Assembly .GetReferencedAssemblies() .Select(Assembly.Load) diff --git a/src/BenchmarkDotNet/Toolchains/Roslyn/RoslynToolchain.cs b/src/BenchmarkDotNet/Toolchains/Roslyn/RoslynToolchain.cs index 7c98c814fc..ed388b26ba 100644 --- a/src/BenchmarkDotNet/Toolchains/Roslyn/RoslynToolchain.cs +++ b/src/BenchmarkDotNet/Toolchains/Roslyn/RoslynToolchain.cs @@ -33,7 +33,7 @@ public override bool IsSupported(BenchmarkCase benchmarkCase, ILogger logger, IR return false; } - if (benchmarkCase.Job.HasValue(InfrastructureMode.BuildConfigurationCharacteristic) + if (benchmarkCase.Job.HasValue(InfrastructureMode.BuildConfigurationCharacteristic) && benchmarkCase.Job.ResolveValue(InfrastructureMode.BuildConfigurationCharacteristic, resolver) != InfrastructureMode.ReleaseConfigurationName) { logger.WriteLineError("The Roslyn toolchain does not allow to rebuild source project, so defining custom build configuration makes no sense"); diff --git a/src/BenchmarkDotNet/Toolchains/Roslyn/RoslynWorkarounds.cs b/src/BenchmarkDotNet/Toolchains/Roslyn/RoslynWorkarounds.cs index 952fbe9bc1..5743963d90 100644 --- a/src/BenchmarkDotNet/Toolchains/Roslyn/RoslynWorkarounds.cs +++ b/src/BenchmarkDotNet/Toolchains/Roslyn/RoslynWorkarounds.cs @@ -10,7 +10,7 @@ internal static CSharpCompilationOptions WithIgnoreCorLibraryDuplicatedTypes(thi // this prevents from // The type 'ValueTuple' exists in both 'System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' and 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' // idea taken from: https://github.com/OmniSharp/omnisharp-roslyn/pull/785 - + var topLevelBinderFlagsProperty = typeof(CSharpCompilationOptions).GetProperty("TopLevelBinderFlags", BindingFlags.Instance | BindingFlags.NonPublic); var binderFlagsType = typeof(CSharpCompilationOptions).GetTypeInfo().Assembly.GetType("Microsoft.CodeAnalysis.CSharp.BinderFlags"); diff --git a/src/BenchmarkDotNet/Toolchains/Toolchain.cs b/src/BenchmarkDotNet/Toolchains/Toolchain.cs index 7b475ba186..a980dff45c 100644 --- a/src/BenchmarkDotNet/Toolchains/Toolchain.cs +++ b/src/BenchmarkDotNet/Toolchains/Toolchain.cs @@ -62,7 +62,7 @@ internal static bool InvalidCliPath(string customDotNetCliPath, BenchmarkCase be logger.WriteLineError($"BenchmarkDotNet requires dotnet cli to be installed or path to local dotnet cli provided in explicit way using `--cli` argument, benchmark '{benchmarkCase.DisplayInfo}' will not be executed"); return true; } - + if (!string.IsNullOrEmpty(customDotNetCliPath) && !File.Exists(customDotNetCliPath)) { logger.WriteLineError($"Provided custom dotnet cli path does not exist, benchmark '{benchmarkCase.DisplayInfo}' will not be executed"); diff --git a/src/BenchmarkDotNet/Toolchains/ToolchainExtensions.cs b/src/BenchmarkDotNet/Toolchains/ToolchainExtensions.cs index 51800355ce..ca6610fee1 100644 --- a/src/BenchmarkDotNet/Toolchains/ToolchainExtensions.cs +++ b/src/BenchmarkDotNet/Toolchains/ToolchainExtensions.cs @@ -49,7 +49,7 @@ internal static IToolchain GetToolchain(this Runtime runtime, Descriptor descrip return InProcessEmitToolchain.Instance; if (coreRuntime.TargetFrameworkMoniker != TargetFrameworkMoniker.NotRecognized) return GetToolchain(coreRuntime.TargetFrameworkMoniker); - + return CsProjCoreToolchain.From(new DotNetCli.NetCoreAppSettings(coreRuntime.MsBuildMoniker, null, coreRuntime.Name)); case CoreRtRuntime coreRtRuntime: diff --git a/src/BenchmarkDotNet/Validators/BaselineValidator.cs b/src/BenchmarkDotNet/Validators/BaselineValidator.cs index 463403c734..085710e3a5 100644 --- a/src/BenchmarkDotNet/Validators/BaselineValidator.cs +++ b/src/BenchmarkDotNet/Validators/BaselineValidator.cs @@ -20,7 +20,7 @@ public IEnumerable Validate(ValidationParameters input) var benchmarkLogicalGroups = allBenchmarks .Select(benchmark => orderProvider.GetLogicalGroupKey(allBenchmarks, benchmark)) .ToArray(); - + var logicalGroups = benchmarkLogicalGroups.Distinct().ToArray(); foreach (string logicalGroup in logicalGroups) { @@ -29,17 +29,17 @@ public IEnumerable Validate(ValidationParameters input) int jobBaselineCount = benchmarks.Select(b => b.Job).Distinct().Count(it => it.Meta.Baseline); string className = benchmarks.First().Descriptor.Type.Name; - if (methodBaselineCount > 1) + if (methodBaselineCount > 1) yield return CreateError("benchmark method", "Baseline = true", logicalGroup, className, methodBaselineCount.ToString()); - if (jobBaselineCount > 1) + if (jobBaselineCount > 1) yield return CreateError("job", "Baseline = true", logicalGroup, className, jobBaselineCount.ToString()); } } - private ValidationError CreateError(string subject, string property, string groupName, string className, string actual) => + private ValidationError CreateError(string subject, string property, string groupName, string className, string actual) => new ValidationError( - TreatsWarningsAsErrors, + TreatsWarningsAsErrors, $"Only 1 {subject} in a group can have \"{property}\" applied to it, group {groupName} in class {className} has {actual}"); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Validators/CompilationValidator.cs b/src/BenchmarkDotNet/Validators/CompilationValidator.cs index 043017ad44..5fc72e9dc2 100644 --- a/src/BenchmarkDotNet/Validators/CompilationValidator.cs +++ b/src/BenchmarkDotNet/Validators/CompilationValidator.cs @@ -63,7 +63,7 @@ private static IEnumerable ValidateBindingModifiers(IEnumerable $"Benchmarked method `{benchmark.Descriptor.WorkloadMethod.Name}` is static. Benchmarks MUST be instance methods, static methods are not supported.", benchmark )); - + private static bool IsValidCSharpIdentifier(string identifier) // F# allows to use whitespaces as names #479 => !string.IsNullOrEmpty(identifier) && (char.IsLetter(identifier[0]) || identifier[0] == Underscore) // An identifier must start with a letter or an underscore diff --git a/src/BenchmarkDotNet/Validators/CompositeValidator.cs b/src/BenchmarkDotNet/Validators/CompositeValidator.cs index b43495663d..89b25a68dc 100644 --- a/src/BenchmarkDotNet/Validators/CompositeValidator.cs +++ b/src/BenchmarkDotNet/Validators/CompositeValidator.cs @@ -13,10 +13,10 @@ internal class CompositeValidator : IValidator /// /// returns true if any of the validators has TreatsWarningsAsErrors == true /// - public bool TreatsWarningsAsErrors + public bool TreatsWarningsAsErrors => validators.Any(validator => validator.TreatsWarningsAsErrors); - public IEnumerable Validate(ValidationParameters validationParameters) + public IEnumerable Validate(ValidationParameters validationParameters) => validators.SelectMany(validator => validator.Validate(validationParameters)).Distinct(); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Validators/DeferredExecutionValidator.cs b/src/BenchmarkDotNet/Validators/DeferredExecutionValidator.cs index 356794c149..d0bda6ed28 100644 --- a/src/BenchmarkDotNet/Validators/DeferredExecutionValidator.cs +++ b/src/BenchmarkDotNet/Validators/DeferredExecutionValidator.cs @@ -13,7 +13,7 @@ public class DeferredExecutionValidator : IValidator public static readonly IValidator FailOnError = new DeferredExecutionValidator(true); private DeferredExecutionValidator(bool failOnError) => TreatsWarningsAsErrors = failOnError; - + public bool TreatsWarningsAsErrors { get; } public IEnumerable Validate(ValidationParameters validationParameters) @@ -30,10 +30,10 @@ private bool IsDeferredExecution(Type returnType) { if (returnType.IsByRef && !returnType.IsGenericType) return IsDeferredExecution(returnType.GetElementType()); - + if (returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(Task<>) || returnType.GetGenericTypeDefinition() == typeof(ValueTask<>))) return IsDeferredExecution(returnType.GetGenericArguments().Single()); - + if (returnType == typeof(IEnumerable) || returnType == typeof(IQueryable)) return true; diff --git a/src/BenchmarkDotNet/Validators/GenericBenchmarksValidator.cs b/src/BenchmarkDotNet/Validators/GenericBenchmarksValidator.cs index 1f78ea44cb..45ef7b5cc5 100644 --- a/src/BenchmarkDotNet/Validators/GenericBenchmarksValidator.cs +++ b/src/BenchmarkDotNet/Validators/GenericBenchmarksValidator.cs @@ -8,9 +8,9 @@ namespace BenchmarkDotNet.Validators public class GenericBenchmarksValidator : IValidator { public static readonly IValidator DontFailOnError = new GenericBenchmarksValidator(); - + public bool TreatsWarningsAsErrors => false; - + public IEnumerable Validate(ValidationParameters validationParameters) => validationParameters .Benchmarks diff --git a/src/BenchmarkDotNet/Validators/ParamsAllValuesValidator.cs b/src/BenchmarkDotNet/Validators/ParamsAllValuesValidator.cs index a0a65d33ec..f146bd72ae 100644 --- a/src/BenchmarkDotNet/Validators/ParamsAllValuesValidator.cs +++ b/src/BenchmarkDotNet/Validators/ParamsAllValuesValidator.cs @@ -17,7 +17,7 @@ private ParamsAllValuesValidator() { } private const BindingFlags reflectionFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; - public IEnumerable Validate(ValidationParameters input) => + public IEnumerable Validate(ValidationParameters input) => input.Benchmarks .Select(benchmark => benchmark.Descriptor.Type) .Distinct() @@ -37,7 +37,7 @@ private bool IsNullable(Type paramType, out Type underlyingType) { underlyingType = Nullable.GetUnderlyingType(paramType); return underlyingType != null; - } + } private ValidationError GetErrorOrDefault(Type parameterType) { diff --git a/src/BenchmarkDotNet/Validators/RunModeValidator.cs b/src/BenchmarkDotNet/Validators/RunModeValidator.cs index 2d452046f8..7a7904c108 100644 --- a/src/BenchmarkDotNet/Validators/RunModeValidator.cs +++ b/src/BenchmarkDotNet/Validators/RunModeValidator.cs @@ -35,10 +35,10 @@ public IEnumerable Validate(ValidationParameters validationPara yield return new ValidationError(true, message, benchmark); } } - + foreach (var validationError in ValidateMinMax(run, resolver, benchmark, RunMode.MinIterationCountCharacteristic, RunMode.MaxIterationCountCharacteristic)) yield return validationError; - + foreach (var validationError in ValidateMinMax(run, resolver, benchmark, RunMode.MinWarmupIterationCountCharacteristic, RunMode.MaxWarmupIterationCountCharacteristic)) yield return validationError; } @@ -48,10 +48,10 @@ private static IEnumerable ValidateMinMax(RunMode run, Composit Characteristic minCharacteristic, Characteristic maxCharacteristic) { string GetName(Characteristic characteristic) => $"{characteristic.DeclaringType.Name}.{characteristic.Id}"; - + int minCount = run.ResolveValue(minCharacteristic, resolver); int maxCount = run.ResolveValue(maxCharacteristic, resolver); - + if (minCount <= 0) yield return new ValidationError(true, $"{GetName(minCharacteristic)} must be greater than zero (was {minCount})", benchmark); diff --git a/src/BenchmarkDotNet/Validators/ValidationError.cs b/src/BenchmarkDotNet/Validators/ValidationError.cs index a43b56d011..4d8526b87b 100644 --- a/src/BenchmarkDotNet/Validators/ValidationError.cs +++ b/src/BenchmarkDotNet/Validators/ValidationError.cs @@ -16,7 +16,7 @@ public ValidationError(bool isCritical, string message, BenchmarkCase benchmarkC [PublicAPI] public bool IsCritical { get; } [PublicAPI] public string Message { get; } [PublicAPI] public BenchmarkCase BenchmarkCase { get; } - + public override string ToString() => Message; public bool Equals(ValidationError other) diff --git a/src/BenchmarkDotNet/Validators/ValidationErrorReporter.cs b/src/BenchmarkDotNet/Validators/ValidationErrorReporter.cs index 9ebe7f5ead..7afc00765c 100644 --- a/src/BenchmarkDotNet/Validators/ValidationErrorReporter.cs +++ b/src/BenchmarkDotNet/Validators/ValidationErrorReporter.cs @@ -7,7 +7,7 @@ namespace BenchmarkDotNet.Validators public static class ValidationErrorReporter { public const string ConsoleErrorPrefix = "// ERROR: "; - + [UsedImplicitly] // Generated benchmarks public static bool ReportIfAny(IEnumerable validationErrors, IHost host) { diff --git a/tests/BenchmarkDotNet.IntegrationTests.DisabledOptimizations/OptimizationsDisabledInCsproj.cs b/tests/BenchmarkDotNet.IntegrationTests.DisabledOptimizations/OptimizationsDisabledInCsproj.cs index ad356928ec..a9e05e1354 100644 --- a/tests/BenchmarkDotNet.IntegrationTests.DisabledOptimizations/OptimizationsDisabledInCsproj.cs +++ b/tests/BenchmarkDotNet.IntegrationTests.DisabledOptimizations/OptimizationsDisabledInCsproj.cs @@ -4,7 +4,7 @@ using BenchmarkDotNet.Validators; namespace BenchmarkDotNet.IntegrationTests.DisabledOptimizations -{ +{ internal class JitOptimizationsValidatorConfig : ManualConfig { public JitOptimizationsValidatorConfig() diff --git a/tests/BenchmarkDotNet.IntegrationTests.ManualRunning/LocalCoreRtToolchainTests.cs b/tests/BenchmarkDotNet.IntegrationTests.ManualRunning/LocalCoreRtToolchainTests.cs index fd9d66dde2..2fa010de0b 100644 --- a/tests/BenchmarkDotNet.IntegrationTests.ManualRunning/LocalCoreRtToolchainTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests.ManualRunning/LocalCoreRtToolchainTests.cs @@ -14,7 +14,7 @@ namespace BenchmarkDotNet.IntegrationTests.ManualRunning /// then update the hardcoded path /// and run following command from console: /// dotnet test -c Release -f netcoreapp2.1 --filter "FullyQualifiedName~BenchmarkDotNet.IntegrationTests.ManualRunning.LocalCoreRtToolchainTests" - /// + /// /// in perfect world we would do this OOB for you, but building CoreRT /// so it's not part of our CI jobs /// diff --git a/tests/BenchmarkDotNet.IntegrationTests/AllSetupAndCleanupTest.cs b/tests/BenchmarkDotNet.IntegrationTests/AllSetupAndCleanupTest.cs index 5c041022ea..5e7e8b97f6 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/AllSetupAndCleanupTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/AllSetupAndCleanupTest.cs @@ -21,14 +21,14 @@ public class AllSetupAndCleanupTest : BenchmarkTestExecutor private readonly string[] expectedLogLines = { "// ### Called: GlobalSetup", - + "// ### Called: IterationSetup (1)", // MainWarmup1 "// ### Called: Benchmark", // MainWarmup1 "// ### Called: IterationCleanup (1)", // MainWarmup1 "// ### Called: IterationSetup (2)", // MainWarmup2 "// ### Called: Benchmark", // MainWarmup2 "// ### Called: IterationCleanup (2)", // MainWarmup2 - + "// ### Called: IterationSetup (3)", // MainTarget1 "// ### Called: Benchmark", // MainTarget1 "// ### Called: IterationCleanup (3)", // MainTarget1 @@ -38,7 +38,7 @@ public class AllSetupAndCleanupTest : BenchmarkTestExecutor "// ### Called: IterationSetup (5)", // MainTarget3 "// ### Called: Benchmark", // MainTarget3 "// ### Called: IterationCleanup (5)", // MainTarget3 - + "// ### Called: GlobalCleanup" }; @@ -52,7 +52,7 @@ public void AllSetupAndCleanupMethodRunsTest() var config = CreateSimpleConfig(logger, miniJob); CanExecute(config); - + var actualLogLines = logger.GetLog().Split('\r', '\n').Where(line => line.StartsWith(Prefix)).ToArray(); foreach (string line in actualLogLines) Output.WriteLine(line); diff --git a/tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs b/tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs index deb83f8e68..5eea5a1d0b 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs @@ -34,11 +34,11 @@ public void WhenInvalidCommandLineArgumentIsPassedAnErrorMessageIsDisplayedAndNo var summaries = BenchmarkSwitcher .FromTypes(Array.Empty()) .Run(new[] { "--DOES_NOT_EXIST" }, config); - + Assert.Empty(summaries); Assert.Contains("Option 'DOES_NOT_EXIST' is unknown.", logger.GetLog()); } - + [Fact] public void WhenUserAsksForInfoAnInfoIsDisplayedAndNoBenchmarksAreExecuted() { @@ -48,7 +48,7 @@ public void WhenUserAsksForInfoAnInfoIsDisplayedAndNoBenchmarksAreExecuted() var summaries = BenchmarkSwitcher .FromTypes(Array.Empty()) .Run(new[] { "--info" }, config); - + Assert.Empty(summaries); Assert.Contains(HostEnvironmentInfo.GetInformation(), logger.GetLog()); } @@ -62,7 +62,7 @@ public void WhenInvalidTypeIsProvidedAnErrorMessageIsDisplayedAndNoBenchmarksAre var summaries = BenchmarkSwitcher .FromTypes(new [] { typeof(ClassC) }) .Run(new[] { "--filter", "*" }, config); - + Assert.Empty(summaries); Assert.Contains("Type BenchmarkDotNet.IntegrationTests.ClassC is invalid.", logger.GetLog()); } @@ -76,7 +76,7 @@ public void WhenNoTypesAreProvidedAnErrorMessageIsDisplayedAndNoBenchmarksAreExe var summaries = BenchmarkSwitcher .FromTypes(Array.Empty()) .Run(new[] { "--filter", "*" }, config); - + Assert.Empty(summaries); Assert.Contains("No benchmarks to choose from. Make sure you provided public non-sealed non-static types with public [Benchmark] methods.", logger.GetLog()); } @@ -91,11 +91,11 @@ public void WhenFilterReturnsNothingAnErrorMessageIsDisplayedAndNoBenchmarksAreE var summaries = BenchmarkSwitcher .FromTypes(new [] { typeof(ClassA), typeof(ClassB) }) .Run(new[] { "--filter", filter }, config); - + Assert.Empty(summaries); Assert.Contains($"The filter '{filter}' that you have provided returned 0 benchmarks.", logger.GetLog()); } - + [Fact] public void WhenUserAsksToPrintAListWePrintIt() { @@ -105,12 +105,12 @@ public void WhenUserAsksToPrintAListWePrintIt() var summaries = BenchmarkSwitcher .FromTypes(new [] { typeof(ClassA) }) .Run(new[] { "--list", "flat" }, config); - + Assert.Empty(summaries); Assert.Contains("BenchmarkDotNet.IntegrationTests.ClassA.Method1", logger.GetLog()); Assert.Contains("BenchmarkDotNet.IntegrationTests.ClassA.Method2", logger.GetLog()); } - + [Fact] public void WhenUserAsksToPrintAListAndProvidesAFilterWePrintFilteredList() { @@ -120,7 +120,7 @@ public void WhenUserAsksToPrintAListAndProvidesAFilterWePrintFilteredList() var summaries = BenchmarkSwitcher .FromTypes(new [] { typeof(ClassA) }) .Run(new[] { "--list", "flat", "--filter", "*.Method1" }, config); - + Assert.Empty(summaries); Assert.Contains("BenchmarkDotNet.IntegrationTests.ClassA.Method1", logger.GetLog()); Assert.DoesNotContain("BenchmarkDotNet.IntegrationTests.ClassA.Method2", logger.GetLog()); @@ -187,11 +187,11 @@ public void WhenUserDoesNotProvideFilterOrCategoriesViaCommandLineWeAskToChooseB var summaries = new BenchmarkSwitcher(userInteractionMock) .With(new [] { typeof(WithDryAttributeAndCategory) }) .Run(Array.Empty(), config); - + Assert.Empty(summaries); // summaries is empty because the returnValue configured for mock returns 0 types Assert.Equal(1, userInteractionMock.AskUserCalledTimes); } - + [Theory] [InlineData("--allCategories")] [InlineData("--anyCategories")] @@ -201,7 +201,7 @@ public void WhenUserProvidesCategoriesWithoutFiltersWeDontAskToChooseBenchmarkJu var config = ManualConfig.CreateEmpty().With(logger); var types = new[] { typeof(WithDryAttributeAndCategory) }; var userInteractionMock = new UserInteractionMock(returnValue: types); - + var summaries = new BenchmarkSwitcher(userInteractionMock) .With(types) .Run(new [] { categoriesConsoleLineArgument, TestCategory }, config); @@ -209,7 +209,7 @@ public void WhenUserProvidesCategoriesWithoutFiltersWeDontAskToChooseBenchmarkJu Assert.Single(summaries); Assert.Equal(0, userInteractionMock.AskUserCalledTimes); } - + [Theory] [InlineData("--allCategories")] [InlineData("--anyCategories")] @@ -219,7 +219,7 @@ public void WhenUserProvidesCategoriesWithtFiltersWeDontAskToChooseBenchmarkJust var config = ManualConfig.CreateEmpty().With(logger); var types = new[] { typeof(WithDryAttributeAndCategory) }; var userInteractionMock = new UserInteractionMock(returnValue: types); - + var summaries = new BenchmarkSwitcher(userInteractionMock) .With(types) .Run(new [] { categoriesConsoleLineArgument, TestCategory, "--filter", "nothing" }, config); @@ -255,17 +255,17 @@ public void WhenJobIsDefinedInTheConfigAndArgumentsDontContainJobArgumentOnlySin var switcher = new BenchmarkSwitcher(types); MockExporter mockExporter = new MockExporter(); var configWithJobDefined = ManualConfig.CreateEmpty().With(mockExporter).With(Job.Dry); - + var results = switcher.Run(new[] { "--filter", "*Method3" }, configWithJobDefined); Assert.True(mockExporter.exported); - + Assert.Single(results); Assert.Single(results.SelectMany(r => r.BenchmarksCases)); Assert.Single(results.SelectMany(r => r.BenchmarksCases.Select(bc => bc.Job))); Assert.True(results.All(r => r.BenchmarksCases.All(bc => bc.Job == Job.Dry))); } - + [Fact] public void WhenJobIsDefinedViaAttributeAndArgumentsDontContainJobArgumentOnlySingleJobIsUsed() { @@ -273,17 +273,17 @@ public void WhenJobIsDefinedViaAttributeAndArgumentsDontContainJobArgumentOnlySi var switcher = new BenchmarkSwitcher(types); MockExporter mockExporter = new MockExporter(); var configWithoutJobDefined = ManualConfig.CreateEmpty().With(mockExporter); - + var results = switcher.Run(new[] { "--filter", "*WithDryAttribute*" }, configWithoutJobDefined); Assert.True(mockExporter.exported); - + Assert.Single(results); Assert.Single(results.SelectMany(r => r.BenchmarksCases)); Assert.Single(results.SelectMany(r => r.BenchmarksCases.Select(bc => bc.Job))); Assert.True(results.All(r => r.BenchmarksCases.All(bc => bc.Job == Job.Dry))); } - + [Fact] public void JobNotDefinedButStillBenchmarkIsExecuted() { @@ -291,11 +291,11 @@ public void JobNotDefinedButStillBenchmarkIsExecuted() var switcher = new BenchmarkSwitcher(types); MockExporter mockExporter = new MockExporter(); var configWithoutJobDefined = ManualConfig.CreateEmpty().With(mockExporter); - + var results = switcher.Run(new[] { "--filter", "*" }, configWithoutJobDefined); - + Assert.True(mockExporter.exported); - + Assert.Single(results); Assert.Single(results.SelectMany(r => r.BenchmarksCases)); Assert.Single(results.SelectMany(r => r.BenchmarksCases.Select(bc => bc.Job))); @@ -390,7 +390,7 @@ public class WithDryAttributeAndCategory [Benchmark] public void Method() { } } - + public class JustBenchmark { [Benchmark] diff --git a/tests/BenchmarkDotNet.IntegrationTests/BenchmarkTestExecutor.cs b/tests/BenchmarkDotNet.IntegrationTests/BenchmarkTestExecutor.cs index d4eea24ce3..36eed8f57f 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/BenchmarkTestExecutor.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/BenchmarkTestExecutor.cs @@ -25,7 +25,7 @@ protected BenchmarkTestExecutor(ITestOutputHelper output) } /// - /// Runs Benchmarks with the most simple config (SingleRunFastConfig) + /// Runs Benchmarks with the most simple config (SingleRunFastConfig) /// combined with any benchmark config applied to TBenchmark (via an attribute) /// By default will verify if every benchmark was successfully executed /// @@ -39,7 +39,7 @@ public Reports.Summary CanExecute(IConfig config = null, bool fullVa } /// - /// Runs Benchmarks with the most simple config (SingleRunFastConfig) + /// Runs Benchmarks with the most simple config (SingleRunFastConfig) /// combined with any benchmark config applied to Type (via an attribute) /// By default will verify if every benchmark was successfully executed /// @@ -75,7 +75,7 @@ protected Reports.Summary CanExecute(Type type, IConfig config = null, bool full Assert.True(summary.Reports.All(r => r.ExecuteResults != null), "The following benchmarks don't have any execution results: " + string.Join(", ", summary.Reports.Where(r => r.ExecuteResults == null).Select(r => r.BenchmarkCase.DisplayInfo))); - + Assert.True(summary.Reports.All(r => r.ExecuteResults.Any(er => er.FoundExecutable && er.Data.Any())), "All reports should have at least one \"ExecuteResult\" with \"FoundExecutable\" = true and at least one \"Data\" item"); diff --git a/tests/BenchmarkDotNet.IntegrationTests/BuildTimeoutTests.cs b/tests/BenchmarkDotNet.IntegrationTests/BuildTimeoutTests.cs index 6ea972b278..43e137d9cd 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/BuildTimeoutTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/BuildTimeoutTests.cs @@ -19,11 +19,11 @@ public void WhenBuildTakesMoreTimeThanTheTimeoutTheBuildIsCancelled() { if (!RuntimeInformation.Is64BitPlatform()) // CoreRT does not support 32bit yet return; - + // we use CoreRT on purpose because it takes a LOT of time to build it // so we can be sure that timeout = 1s should fail! var timeout = TimeSpan.FromSeconds(1); - + var config = ManualConfig.CreateEmpty() .With(Job.Dry .With(CoreRtRuntime.CoreRt21) diff --git a/tests/BenchmarkDotNet.IntegrationTests/CoreRtTests.cs b/tests/BenchmarkDotNet.IntegrationTests/CoreRtTests.cs index 4245b4beeb..ae2476497c 100755 --- a/tests/BenchmarkDotNet.IntegrationTests/CoreRtTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/CoreRtTests.cs @@ -19,7 +19,7 @@ public void LatestCoreRtVersionIsSupported() { if (!RuntimeInformation.Is64BitPlatform()) // CoreRT does not support 32bit yet return; - + var config = ManualConfig.CreateEmpty() .With(Job.Dry .With(CoreRtRuntime.GetCurrentVersion()) diff --git a/tests/BenchmarkDotNet.IntegrationTests/CustomEngineTests.cs b/tests/BenchmarkDotNet.IntegrationTests/CustomEngineTests.cs index 3d58cffa47..ce0a99690b 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/CustomEngineTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/CustomEngineTests.cs @@ -62,8 +62,8 @@ public IEngine CreateReadyToRun(EngineParameters engineParameters) GlobalCleanupAction = engineParameters.GlobalCleanupAction, GlobalSetupAction = engineParameters.GlobalSetupAction }; - - engine.GlobalSetupAction?.Invoke(); // engine factory is now supposed to create an engine which is ready to run (hence the method name change) + + engine.GlobalSetupAction?.Invoke(); // engine factory is now supposed to create an engine which is ready to run (hence the method name change) return engine; } @@ -85,7 +85,7 @@ public RunResults Run() } public void Dispose() => GlobalCleanupAction?.Invoke(); - + public IHost Host { get; } public void WriteLine() { } public void WriteLine(string line) { } diff --git a/tests/BenchmarkDotNet.IntegrationTests/Diagnosers/ProcessMetricsTests.cs b/tests/BenchmarkDotNet.IntegrationTests/Diagnosers/ProcessMetricsTests.cs index 8697d27c55..3a7c096f86 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/Diagnosers/ProcessMetricsTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/Diagnosers/ProcessMetricsTests.cs @@ -15,17 +15,17 @@ public class ProcessMetricsTests public void TheNumberOfStopEventsMustBeEqualToStartEvents() { var sut = new ProcessMetrics(); - + sut.HandleIterationEvent(0, IterationMode.Overhead, 100); // start but no stop later on Assert.Throws(() => sut.CalculateMetrics(null, Array.Empty())); } - + [Fact] public void TheNumberOfTotalOperationsPerIterationIsTheSameForAllIterations() { var sut = new ProcessMetrics(); - + sut.HandleIterationEvent(0, IterationMode.Workload, 100); // start Assert.Throws(() => sut.HandleIterationEvent(0, IterationMode.Workload, 100 + 1)); @@ -38,36 +38,36 @@ public void MetricsAreCorrectlyCalculatedPerIteration() const int interval = 100; const ulong ip = 12345; const long totalOperations = 100; - + var sut = new ProcessMetrics(); - + for (int relativeTimestamp = 0; relativeTimestamp < 20; relativeTimestamp++) { sut.HandleIterationEvent(relativeTimestamp, IterationMode.Overhead, totalOperations); // Overhead iteration start at i - + sut.HandleNewSample(relativeTimestamp + 0.1, ip, profileSourceId); // Engine overhead produces one PMC event per iteration - + sut.HandleIterationEvent(relativeTimestamp + 0.5, IterationMode.Overhead, totalOperations); // Overhead iteration stop at i + 0.5 } - + for (int relativeTimestamp = 20; relativeTimestamp < 40; relativeTimestamp++) { sut.HandleIterationEvent(relativeTimestamp, IterationMode.Workload, totalOperations); // Workload iteration start at i - + sut.HandleNewSample(relativeTimestamp + 0.1, ip, profileSourceId); // Engine overhead produces one PMC event per iteration sut.HandleNewSample(relativeTimestamp + 0.2, ip, profileSourceId); // benchmarked code sut.HandleNewSample(relativeTimestamp + 0.3, ip, profileSourceId); // benchmarked code sut.HandleNewSample(relativeTimestamp + 0.4, ip, profileSourceId); // benchmarked code - + sut.HandleIterationEvent(relativeTimestamp + 0.5, IterationMode.Workload, totalOperations); // Workload iteration stop at i + 0.5 } var metrics = sut.CalculateMetrics( - new Dictionary { {profileSourceId, interval }}, + new Dictionary { {profileSourceId, interval }}, new []{ new PreciseMachineCounter(profileSourceId, "test", HardwareCounter.InstructionRetired, interval), }); const ulong expected = (4 * interval - interval) / totalOperations; // every workload was 4 events, the overhead was one and totalOperations times per iteration - + Assert.Equal(expected, metrics.Single().Value); } } diff --git a/tests/BenchmarkDotNet.IntegrationTests/DisassemblyDiagnoserTests.cs b/tests/BenchmarkDotNet.IntegrationTests/DisassemblyDiagnoserTests.cs index f0a16c389a..51e0f4cc76 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/DisassemblyDiagnoserTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/DisassemblyDiagnoserTests.cs @@ -118,7 +118,7 @@ public class WithInlineable { [Benchmark] public void JustReturn() { } } - + [TheoryWindowsOnly(WindowsOnly)] [MemberData(nameof(GetAllJits))] [Trait(Constants.Category, Constants.BackwardCompatibilityCategory)] diff --git a/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs b/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs index 6ba93a27ab..c603deab0f 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs @@ -141,7 +141,7 @@ public override void ExportToLog(Summary summary, ILogger logger) } } - private ImmutableArray CreateReports(Type[] types, IConfig config = null) + private ImmutableArray CreateReports(Type[] types, IConfig config = null) => CreateBenchmarks(types, config).Select(CreateReport).ToImmutableArray(); private BenchmarkCase[] CreateBenchmarks(Type[] types, IConfig config) diff --git a/tests/BenchmarkDotNet.IntegrationTests/GlobalCleanupAttributeTargetTest.cs b/tests/BenchmarkDotNet.IntegrationTests/GlobalCleanupAttributeTargetTest.cs index 6bb3afe934..e3060151e1 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/GlobalCleanupAttributeTargetTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/GlobalCleanupAttributeTargetTest.cs @@ -29,7 +29,7 @@ public void GlobalCleanupTargetSpecificMethodTest() Assert.Contains(BaselineBenchmarkCalled + Environment.NewLine, log); Assert.True( - log.IndexOf(BaselineBenchmarkCalled + Environment.NewLine) < + log.IndexOf(BaselineBenchmarkCalled + Environment.NewLine) < log.IndexOf(BaselineGlobalCleanupCalled + Environment.NewLine)); Assert.Contains(FirstGlobalCleanupCalled + Environment.NewLine, log); diff --git a/tests/BenchmarkDotNet.IntegrationTests/GlobalSetupAttributeTargetTest.cs b/tests/BenchmarkDotNet.IntegrationTests/GlobalSetupAttributeTargetTest.cs index 018074c6d9..20431f53b9 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/GlobalSetupAttributeTargetTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/GlobalSetupAttributeTargetTest.cs @@ -24,12 +24,12 @@ public void GlobalSetupTargetSpecificMethodTest() var config = CreateSimpleConfig(logger); CanExecute(config); - + string log = logger.GetLog(); Assert.Contains(BaselineGlobalSetupCalled + Environment.NewLine, log); Assert.True( - log.IndexOf(BaselineGlobalSetupCalled + Environment.NewLine) < + log.IndexOf(BaselineGlobalSetupCalled + Environment.NewLine) < log.IndexOf(BaselineBenchmarkCalled + Environment.NewLine)); Assert.Contains(FirstGlobalSetupCalled + Environment.NewLine, log); @@ -78,7 +78,7 @@ public void Benchmark1() Console.WriteLine(FirstBenchmarkCalled); } - + [GlobalSetup(Target = nameof(Benchmark2))] public void GlobalSetup2() { diff --git a/tests/BenchmarkDotNet.IntegrationTests/JitRuntimeValidationTest.cs b/tests/BenchmarkDotNet.IntegrationTests/JitRuntimeValidationTest.cs index c799ec379e..70966c64da 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/JitRuntimeValidationTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/JitRuntimeValidationTest.cs @@ -48,7 +48,7 @@ public void CheckClrOnWindows(Jit jit, Platform platform, string expectedText) { Verify(ClrRuntime.Net461, jit, platform, expectedText); } - + // [TheoryWindowsOnly("CLR is a valid job only on Windows")] // [InlineData(Jit.LegacyJit, Platform.X86, LegacyJitNotAvailableForMono)] // [InlineData(Jit.LegacyJit, Platform.X64, LegacyJitNotAvailableForMono)] diff --git a/tests/BenchmarkDotNet.IntegrationTests/MemoryDiagnoserTests.cs b/tests/BenchmarkDotNet.IntegrationTests/MemoryDiagnoserTests.cs index 3af03b9536..875736072e 100755 --- a/tests/BenchmarkDotNet.IntegrationTests/MemoryDiagnoserTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/MemoryDiagnoserTests.cs @@ -38,7 +38,7 @@ public static IEnumerable GetToolchains() { new object[] { Job.Default.GetToolchain() }, new object[] { InProcessEmitToolchain.Instance }, -#if NETCOREAPP2_1 +#if NETCOREAPP2_1 // we don't want to test CoreRT twice (for .NET 4.6 and Core 2.1) when running the integration tests (these tests take a lot of time) // we test against specific version to keep this test stable new object[] { CoreRtToolchain.CreateBuilder().UseCoreRtNuGet(microsoftDotNetILCompilerVersion: "1.0.0-alpha-27408-02").ToToolchain() } diff --git a/tests/BenchmarkDotNet.IntegrationTests/NugetReferenceTests.cs b/tests/BenchmarkDotNet.IntegrationTests/NugetReferenceTests.cs index 9cda2b82a4..052a7b67a0 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/NugetReferenceTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/NugetReferenceTests.cs @@ -38,7 +38,7 @@ public void RoslynToolchainDoesNotSupportNuGetPackageDependency() var unsupportedJobConfig = CreateSimpleConfig(job: unsupportedJob); var unsupportedJobBenchmark = BenchmarkConverter.TypeToBenchmarks(typeof(WithCallToNewtonsoft), unsupportedJobConfig); var unsupportedJobLogger = new CompositeLogger(unsupportedJobConfig.GetLoggers().ToImmutableHashSet()); - foreach (var benchmarkCase in unsupportedJobBenchmark.BenchmarksCases) + foreach (var benchmarkCase in unsupportedJobBenchmark.BenchmarksCases) { Assert.False(toolchain.IsSupported(benchmarkCase, unsupportedJobLogger, BenchmarkRunnerClean.DefaultResolver)); } diff --git a/tests/BenchmarkDotNet.IntegrationTests/ParamsAttributeStaticTest.cs b/tests/BenchmarkDotNet.IntegrationTests/ParamsAttributeStaticTest.cs index 3436292326..189a42137c 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/ParamsAttributeStaticTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/ParamsAttributeStaticTest.cs @@ -27,7 +27,7 @@ public void Test() public class ParamsTestStaticProperty { /// - /// Deliberately made the Property "static" to ensure that Params also work okay in this scenario + /// Deliberately made the Property "static" to ensure that Params also work okay in this scenario /// [Params(1, 2)] public static int StaticParamProperty { get; set; } @@ -45,7 +45,7 @@ public void Benchmark() } } } - + public class ParamsTestStaticPrivatePropertyError : BenchmarkTestExecutor { public ParamsTestStaticPrivatePropertyError(ITestOutputHelper output) : base(output) { } diff --git a/tests/BenchmarkDotNet.IntegrationTests/ParamsTests.cs b/tests/BenchmarkDotNet.IntegrationTests/ParamsTests.cs index 8fca774989..dd35836620 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/ParamsTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/ParamsTests.cs @@ -54,7 +54,7 @@ public class ParamsTestPrivatePropertyError public int ParamProperty { get; private set; } private HashSet collectedParams = new HashSet(); - + [Benchmark] public void Benchmark() { @@ -168,7 +168,7 @@ public void Benchmark() [Fact] public void InvalidFileNamesInParamsAreSupported() => CanExecute(); - + public class InvalidFileNamesInParams { [Params("/\\@#$%")] @@ -196,15 +196,15 @@ public void Benchmark(string argument) throw new InvalidOperationException("Wrong character escaping!"); } } - + [Fact] public void ArrayCanBeUsedAsParameter() => CanExecute(); - + public class WithArray { [Params(new[] { 0, 1, 2 })] public int[] Array; - + [Benchmark] public void AcceptingArray() { diff --git a/tests/BenchmarkDotNet.IntegrationTests/ProcessPropertiesTests.cs b/tests/BenchmarkDotNet.IntegrationTests/ProcessPropertiesTests.cs index 1824d9a9ba..11c6a465e5 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/ProcessPropertiesTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/ProcessPropertiesTests.cs @@ -12,7 +12,7 @@ namespace BenchmarkDotNet.IntegrationTests { public class ProcessPropertiesTests : BenchmarkTestExecutor { - public ProcessPropertiesTests(ITestOutputHelper output) + public ProcessPropertiesTests(ITestOutputHelper output) : base(output) { } @@ -49,7 +49,7 @@ public void Ensure() public class CustomAffinity { - public static readonly IntPtr Value = new IntPtr(2); + public static readonly IntPtr Value = new IntPtr(2); [Benchmark] public void Ensure() diff --git a/tests/BenchmarkDotNet.IntegrationTests/ReferencesTests.cs b/tests/BenchmarkDotNet.IntegrationTests/ReferencesTests.cs index f28f26728e..c69c5a67c4 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/ReferencesTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/ReferencesTests.cs @@ -9,11 +9,11 @@ public ReferencesTests(ITestOutputHelper output) : base(output) { } #if CLASSIC [Fact] - public void BenchmarksThatUseTypeFromCustomPathDllAreSupported() + public void BenchmarksThatUseTypeFromCustomPathDllAreSupported() => CanExecute(); [Fact] - public void BenchmarksThatReturnTypeFromCustomPathDllAreSupported() + public void BenchmarksThatReturnTypeFromCustomPathDllAreSupported() => CanExecute(); #endif [Fact] diff --git a/tests/BenchmarkDotNet.IntegrationTests/SetupAndCleanupTests.cs b/tests/BenchmarkDotNet.IntegrationTests/SetupAndCleanupTests.cs index 0ccaa65694..de66000a44 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/SetupAndCleanupTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/SetupAndCleanupTests.cs @@ -36,7 +36,7 @@ public class SetupAndCleanupTests : BenchmarkTestExecutor "// ### First Called: IterationSetup (2)", // MainWarmup2 "// ### First Called: Benchmark", // MainWarmup2 "// ### First Called: IterationCleanup (2)", // MainWarmup2 - + "// ### First Called: IterationSetup (3)", // MainTarget1 "// ### First Called: Benchmark", // MainTarget1 "// ### First Called: IterationCleanup (3)", // MainTarget1 @@ -46,10 +46,10 @@ public class SetupAndCleanupTests : BenchmarkTestExecutor "// ### First Called: IterationSetup (5)", // MainTarget3 "// ### First Called: Benchmark", // MainTarget3 "// ### First Called: IterationCleanup (5)", // MainTarget3 - + "// ### First Called: GlobalCleanup" }; - + private readonly string[] secondExpectedLogLines = { "// ### Second Called: GlobalSetup", @@ -59,7 +59,7 @@ public class SetupAndCleanupTests : BenchmarkTestExecutor "// ### Second Called: IterationSetup (2)", // MainWarmup2 "// ### Second Called: Benchmark", // MainWarmup2 "// ### Second Called: IterationCleanup (2)", // MainWarmup2 - + "// ### Second Called: IterationSetup (3)", // MainTarget1 "// ### Second Called: Benchmark", // MainTarget1 "// ### Second Called: IterationCleanup (3)", // MainTarget1 @@ -69,7 +69,7 @@ public class SetupAndCleanupTests : BenchmarkTestExecutor "// ### Second Called: IterationSetup (5)", // MainTarget3 "// ### Second Called: Benchmark", // MainTarget3 "// ### Second Called: IterationCleanup (5)", // MainTarget3 - + "// ### Second Called: GlobalCleanup" }; @@ -91,7 +91,7 @@ public void AllSetupAndCleanupMethodRunsForSpecificBenchmark() foreach (string line in firstActualLogLines) Output.WriteLine(line); Assert.Equal(firstExpectedLogLines, firstActualLogLines); - + var secondActualLogLines = logger.GetLog().Split('\r', '\n').Where(line => line.StartsWith(SecondPrefix)).ToArray(); foreach (string line in secondActualLogLines) Output.WriteLine(line); @@ -117,7 +117,7 @@ public class Benchmarks [Benchmark] public void FirstBenchmark() => Console.WriteLine(FirstBenchmarkCalled); - + [IterationSetup(Target = nameof(SecondBenchmark))] public void SecondIterationSetup() => Console.WriteLine(SecondIterationSetupCalled + " (" + ++setupCounter + ")"); diff --git a/tests/BenchmarkDotNet.IntegrationTests/ValuesReturnedByBenchmarkTest.cs b/tests/BenchmarkDotNet.IntegrationTests/ValuesReturnedByBenchmarkTest.cs index 9af4543d35..15627867b6 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/ValuesReturnedByBenchmarkTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/ValuesReturnedByBenchmarkTest.cs @@ -57,7 +57,7 @@ public class ValuesReturnedByBenchmark [Benchmark] public ImmutableArray TypeFromNetStandardNuGetPackage() => ImmutableArray.Empty; - + [Benchmark] public ValueTuple TypeInTwoDlls() => new ValueTuple(); @@ -75,7 +75,7 @@ public Result(T field) public Job TypeCalledJob() => new Job(); public class Job { } - + [Benchmark] public NoNamespace TypeWithoutNamespace() => new NoNamespace(); } diff --git a/tests/BenchmarkDotNet.Tests/Analysers/ZeroMeasurementHelperTests.cs b/tests/BenchmarkDotNet.Tests/Analysers/ZeroMeasurementHelperTests.cs index b26e0384b0..2750fabb97 100644 --- a/tests/BenchmarkDotNet.Tests/Analysers/ZeroMeasurementHelperTests.cs +++ b/tests/BenchmarkDotNet.Tests/Analysers/ZeroMeasurementHelperTests.cs @@ -7,20 +7,20 @@ namespace BenchmarkDotNet.Tests.Analysers public class ZeroMeasurementHelperTests { #region OneSampleTests - + // let processor frequency ~ 3.30 GHz private static double ThresholdMock = 0.2702d / 2; - + /* Test distributions inspired by data from method - - public double Sqrt14() + + public double Sqrt14() => Math.Sqrt(1) + Math.Sqrt(2) + Math.Sqrt(3) + Math.Sqrt(4) + Math.Sqrt(5) + Math.Sqrt(6) + Math.Sqrt(7) + Math.Sqrt(8) + Math.Sqrt(9) + Math.Sqrt(10) + Math.Sqrt(11) + Math.Sqrt(12) + Math.Sqrt(13) + Math.Sqrt(14); - - with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU + + with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU and RyuJit x64 */ [Theory] @@ -33,7 +33,7 @@ public void OneSample_Around_One_CPU_Cycle_Method(params double[] distribution) var zeroMeasurement = ZeroMeasurementHelper.CheckZeroMeasurementOneSample(distribution, ThresholdMock); Assert.False(zeroMeasurement); } - + [Theory] [InlineData(0.2703, 0.2701, 0.2703, 0.2701, 0.2703, 0.2701, 0.2703, 0.2701, 0.2703, 0.2701, 0.2703, 0.2701)] public void OneSample_Exactly_One_CPU_Cycle_Method(params double[] distribution) @@ -41,17 +41,17 @@ public void OneSample_Exactly_One_CPU_Cycle_Method(params double[] distribution) var zeroMeasurement = ZeroMeasurementHelper.CheckZeroMeasurementOneSample(distribution, ThresholdMock); Assert.False(zeroMeasurement); } - + /* Data inspired by distribution of benchmark - - [MethodImpl(MethodImplOptions.NoOptimization)] + + [MethodImpl(MethodImplOptions.NoOptimization)] public double Return1() { return 1; } - - with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU + + with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU and RyuJit x64 */ [Theory] @@ -63,7 +63,7 @@ public void OneSample_Less_Than_One_CPU_Cycle_Method(params double[] distributio var zeroMeasurement = ZeroMeasurementHelper.CheckZeroMeasurementOneSample(distribution, ThresholdMock); Assert.True(zeroMeasurement); } - + /* Sometimes appears distributions with all zero values That's definitely zero measurement @@ -75,13 +75,13 @@ public void OneSample_Exactly_Zero_ns_Method(params double[] distribution) var zeroMeasurement = ZeroMeasurementHelper.CheckZeroMeasurementOneSample(distribution, ThresholdMock); Assert.True(zeroMeasurement); } - + /* Test distributions inspired by data from method - + public double Abs() => Math.Abs(A); - - with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU + + with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU and RyuJit x64 */ [Theory] @@ -98,15 +98,15 @@ public void OneSample_Around_Two_CPU_Cycle_Method(params double[] distribution) #region TwoSamplesTests /* - Data inspired by distribution of benchmark (Workload Actual and Overhead Actual measurements) - - [MethodImpl(MethodImplOptions.NoOptimization)] + Data inspired by distribution of benchmark (Workload Actual and Overhead Actual measurements) + + [MethodImpl(MethodImplOptions.NoOptimization)] public double Return1() { return 1; } - - with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU + + with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU and RyuJit x64 */ public static IEnumerable LessThanOneCycleTwoSamples @@ -117,16 +117,16 @@ public static IEnumerable LessThanOneCycleTwoSamples { new object[] { new [] { 2.0037, 2.0062, 2.0066, 2.0073, 2.0089, 2.0103, 2.013, 2.0169, 2.0197, 2.0224, 2.0243, 2.0271, 2.0281, 2.0514, 2.0517 }, new [] { 2.0426, 2.046, 2.0471, 2.0506, 2.0508, 2.0555, 2.0573, 2.0653, 2.0657, 2.0659, 2.0692, 2.0717, 2.0777, 2.0856, 2.0868 } }, - + new object[] { new [] { 2.0186, 2.0196, 2.0207, 2.0208, 2.0208, 2.0211, 2.0213, 2.0215, 2.0288, 2.0315, 2.0326, 2.039, 2.049, 2.055, 2.0598 }, new [] { 2.0151, 2.0192, 2.0226, 2.0248, 2.0271, 2.0276, 2.0298, 2.0339, 2.0411, 2.0429, 2.0458, 2.0501, 2.061, 2.0733, 2.0744 } }, - + new object[] { new [] { 2.0049, 2.0141, 2.0194, 2.0253, 2.0264, 2.0296, 2.0333, 2.0422, 2.0438, 2.044, 2.047, 2.048, 2.0494, 2.0549, 2.0675 }, new [] { 1.9963, 2.0037, 2.0037, 2.0046, 2.0051, 2.007, 2.0166, 2.021, 2.0225, 2.0247, 2.0391, 2.0473, 2.0572, 2.0576, 2.0582 } } }; } } - + [Theory] [MemberData(nameof(LessThanOneCycleTwoSamples))] public void TwoSamples_Less_Than_One_CPU_Cycle_Method(double[] workload, double[] overhead) @@ -134,17 +134,17 @@ public void TwoSamples_Less_Than_One_CPU_Cycle_Method(double[] workload, double[ var zeroMeasurement = ZeroMeasurementHelper.CheckZeroMeasurementTwoSamples(workload, overhead); Assert.True(zeroMeasurement); } - + /* Test distributions inspired by data (Workload Actual and Overhead Actual) from method - - public double Sqrt14() + + public double Sqrt14() => Math.Sqrt(1) + Math.Sqrt(2) + Math.Sqrt(3) + Math.Sqrt(4) + Math.Sqrt(5) + Math.Sqrt(6) + Math.Sqrt(7) + Math.Sqrt(8) + Math.Sqrt(9) + Math.Sqrt(10) + Math.Sqrt(11) + Math.Sqrt(12) + Math.Sqrt(13) + Math.Sqrt(14); - - with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU + + with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU and RyuJit x64 */ public static IEnumerable OneCycleTwoSamples @@ -155,16 +155,16 @@ public static IEnumerable OneCycleTwoSamples { new object[] { new [] { 2.34763, 2.34861, 2.34872, 2.34953, 2.35002, 2.35614, 2.35650, 2.36323, 2.36941, 2.37376, 2.38491, 2.38619, 2.38657, 2.38902, 2.39455 }, new [] { 2.05899, 2.06069, 2.06243, 2.06405, 2.06762, 2.06785, 2.06889, 2.06891, 2.06895, 2.07531, 2.08003, 2.08024, 2.08342, 2.08959 } }, - + new object[] { new [] { 2.36960, 2.37438, 2.37442, 2.38332, 2.38940, 2.39099, 2.39394, 2.39974, 2.40808, 2.41760, 2.41980, 2.42275, 2.42828, 2.42946, 2.43763 }, new [] { 2.06486, 2.06599, 2.07205, 2.07660, 2.07810, 2.07841, 2.08107, 2.08714, 2.10467, 2.10469, 2.11713, 2.12078, 2.12476, 2.12858, 2.13760 } }, - + new object[] { new [] { 2.35046, 2.35630, 2.35788, 2.35801, 2.36632, 2.36841, 2.36925, 2.36980, 2.36998, 2.37153, 2.37330, 2.38491, 2.38732, 2.38853, 2.41052 }, new [] { 2.06291, 2.06545, 2.06763, 2.07381, 2.07568, 2.07810, 2.07894, 2.08153, 2.08264, 2.09000, 2.09814, 2.10082, 2.10107, 2.10576, 2.12841 } } }; } } - + [Theory] [MemberData(nameof(OneCycleTwoSamples))] public void TwoSamples_Around_One_CPU_Cycle_Method(double[] workload, double[] overhead) @@ -175,10 +175,10 @@ public void TwoSamples_Around_One_CPU_Cycle_Method(double[] workload, double[] o /* Test distributions inspired by data (Workload Actual and Overhead Actual) from method - + public double Abs() => Math.Abs(A); - - with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU + + with Intel Core i5-2500 CPU 3.30GHz (Sandy Bridge) CPU and RyuJit x64 */ public static IEnumerable TwoCycleTwoSamples @@ -189,16 +189,16 @@ public static IEnumerable TwoCycleTwoSamples { new object[] { new [] { 2.6561, 2.658, 2.6606, 2.6621, 2.6636, 2.6639, 2.6656, 2.6673, 2.6741, 2.6754, 2.6787, 2.6935, 2.6997, 2.7313, 2.7394 }, new [] { 2.0387, 2.0436, 2.0485, 2.0485, 2.0525, 2.0584, 2.0638, 2.0678, 2.0678, 2.0698, 2.0703, 2.0715, 2.0825, 2.0864 } }, - + new object[] { new [] { 2.6368, 2.6504, 2.652, 2.6541, 2.6607, 2.6642, 2.6698, 2.6749, 2.679, 2.6847, 2.6858, 2.6883, 2.6929, 2.702, 2.7134 }, new [] { 2.04, 2.0461, 2.0481, 2.0485, 2.0502, 2.0523, 2.0547, 2.0602, 2.0613, 2.0677, 2.069, 2.0691, 2.0699, 2.0865 } }, - + new object[] { new [] { 2.6607, 2.6691, 2.67, 2.6741, 2.6753, 2.679, 2.6856, 2.6869, 2.6893, 2.692, 2.6971, 2.7146, 2.7245, 2.7368 }, new [] { 2.0346, 2.054, 2.0655, 2.0673, 2.0718, 2.0748, 2.0766, 2.0839, 2.0856, 2.0869, 2.0924, 2.0968, 2.1129, 2.1148, 2.1328 } } }; } } - + [Theory] [MemberData(nameof(TwoCycleTwoSamples))] public void TwoSamples_Around_Two_CPU_Cycle_Method(double[] workload, double[] overhead) diff --git a/tests/BenchmarkDotNet.Tests/Builders/HostEnvironmentInfoBuilder.cs b/tests/BenchmarkDotNet.Tests/Builders/HostEnvironmentInfoBuilder.cs index 1c05cb52b1..e22862881b 100644 --- a/tests/BenchmarkDotNet.Tests/Builders/HostEnvironmentInfoBuilder.cs +++ b/tests/BenchmarkDotNet.Tests/Builders/HostEnvironmentInfoBuilder.cs @@ -64,7 +64,7 @@ internal class MockHostEnvironmentInfo : HostEnvironmentInfo public MockHostEnvironmentInfo( string architecture, string benchmarkDotNetVersion, Frequency chronometerFrequency, string configuration, string dotNetSdkVersion, HardwareTimerKind hardwareTimerKind, bool hasAttachedDebugger, bool hasRyuJit, bool isConcurrentGC, bool isServerGC, - string jitInfo, string jitModules, string osVersion, CpuInfo cpuInfo, + string jitInfo, string jitModules, string osVersion, CpuInfo cpuInfo, string runtimeVersion, VirtualMachineHypervisor virtualMachineHypervisor) { Architecture = architecture; diff --git a/tests/BenchmarkDotNet.Tests/Columns/StatisticalTestColumnTests.cs b/tests/BenchmarkDotNet.Tests/Columns/StatisticalTestColumnTests.cs index 9e6e146b8f..b6838d6a0e 100644 --- a/tests/BenchmarkDotNet.Tests/Columns/StatisticalTestColumnTests.cs +++ b/tests/BenchmarkDotNet.Tests/Columns/StatisticalTestColumnTests.cs @@ -19,7 +19,7 @@ public void NoDifferenceIfValuesAreTheSame(StatisticalTestKind statisticalTestKi Compare(statisticalTestKind, thresholdUnit, thresholdValue, values, values, "Base"); } - + [Theory] [InlineData(StatisticalTestKind.MannWhitney, ThresholdUnit.Ratio, 0.02)] [InlineData(StatisticalTestKind.Welch, ThresholdUnit.Ratio, 0.02)] @@ -27,10 +27,10 @@ public void RegressionsAreDetected(StatisticalTestKind statisticalTestKind, Thre { var baseline = new[] { 10.0, 10.01, 10.02, 10.0, 10.03, 10.02, 9.99, 9.98, 10.0, 10.02 }; var current = baseline.Select(value => value * 1.03).ToArray(); - + Compare(statisticalTestKind, thresholdUnit, thresholdValue, baseline, current, "Slower"); } - + [Theory] [InlineData(StatisticalTestKind.MannWhitney, ThresholdUnit.Ratio, 0.02)] [InlineData(StatisticalTestKind.Welch, ThresholdUnit.Ratio, 0.02)] @@ -40,10 +40,10 @@ public void CanCompareDifferentSampleSizes(StatisticalTestKind statisticalTestKi var current = baseline .Skip(1) // we skip one element to make sure the sample size is different .Select(value => value * 1.03).ToArray(); - + Compare(statisticalTestKind, thresholdUnit, thresholdValue, baseline, current, "Slower"); } - + [Theory] [InlineData(StatisticalTestKind.MannWhitney, ThresholdUnit.Ratio, 0.02)] [InlineData(StatisticalTestKind.Welch, ThresholdUnit.Ratio, 0.02)] diff --git a/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs b/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs index 677ad9923f..da2b906de7 100644 --- a/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs +++ b/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs @@ -64,7 +64,7 @@ public void SimpleConfigAlternativeVersionParsedCorrectly() Assert.Single(config.GetJobs()); Assert.Contains(Job.Dry, config.GetJobs()); } - + [Fact] public void UserCanSpecifyHowManyTimesTheBenchmarkShouldBeExecuted() { @@ -72,30 +72,30 @@ public void UserCanSpecifyHowManyTimesTheBenchmarkShouldBeExecuted() const int warmupCount = 1; const int iterationTime = 250; const int iterationCount = 20; - + var config = ConfigParser.Parse(new[] { - "--LaunchCount", launchCount.ToString(), + "--LaunchCount", launchCount.ToString(), "--warmupCount", warmupCount.ToString(), "--iterationTime", iterationTime.ToString(), "--iterationCount", iterationCount.ToString() }, new OutputLogger(Output)).config; var job = config.GetJobs().Single(); - + Assert.Equal(launchCount, job.Run.LaunchCount); Assert.Equal(warmupCount, job.Run.WarmupCount); Assert.Equal(TimeInterval.FromMilliseconds(iterationTime), job.Run.IterationTime); Assert.Equal(iterationCount, job.Run.IterationCount); } - + [Fact] public void UserCanEasilyRequestToRunTheBenchmarkOncePerIteration() { var configEasy = ConfigParser.Parse(new[] { "--runOncePerIteration" }, new OutputLogger(Output)).config; var easyJob = configEasy.GetJobs().Single(); - + Assert.Equal(1, easyJob.Run.UnrollFactor); Assert.Equal(1, easyJob.Run.InvocationCount); } @@ -149,7 +149,7 @@ public void CoreRunConfigParsedCorrectlyWhenRuntimeNotSpecified() Assert.Equal(fakeDotnetCliPath, toolchain.CustomDotNetCliPath.FullName); Assert.Equal(fakeRestorePackages, toolchain.RestorePath.FullName); } - + [Fact] public void CoreRunConfigParsedCorrectlyWhenRuntimeSpecified() { @@ -167,7 +167,7 @@ public void CoreRunConfigParsedCorrectlyWhenRuntimeSpecified() Assert.Equal(fakeDotnetCliPath, toolchain.CustomDotNetCliPath.FullName); Assert.Equal(fakeRestorePackages, toolchain.RestorePath.FullName); } - + [Fact] public void UserCanSpecifyMultipleCoreRunPaths() { @@ -182,7 +182,7 @@ public void UserCanSpecifyMultipleCoreRunPaths() Assert.Single(jobs.Where(job => job.GetToolchain() is CoreRunToolchain toolchain && toolchain.SourceCoreRun.FullName == fakeCoreRunPath_2)); Assert.Equal(2, jobs.Select(job => job.Id).Distinct().Count()); // each job must have a unique ID } - + [Fact] public void MonoPathParsedCorrectly() { @@ -202,7 +202,7 @@ public void ClrVersionParsedCorrectly() Assert.Single(config.GetJobs()); Assert.Single(config.GetJobs().Where(job => job.Environment.Runtime is ClrRuntime clr && clr.Version == clrVersion)); } - + [Fact] public void CoreRtPathParsedCorrectly() { @@ -214,7 +214,7 @@ public void CoreRtPathParsedCorrectly() Assert.NotNull(toolchain); Assert.Equal(fakeCoreRtPath.FullName, toolchain.IlcPath); } - + [Theory] [InlineData("netcoreapp2.0")] [InlineData("netcoreapp2.1")] @@ -239,10 +239,10 @@ public void DotNetCliParsedCorrectly(string tfm) [InlineData(ConfigOptions.StopOnFirstError, "--stopOnFirstError")] [InlineData(ConfigOptions.DisableLogFile, "--disableLogFile" )] [InlineData( - ConfigOptions.JoinSummary | - ConfigOptions.KeepBenchmarkFiles | - ConfigOptions.DontOverwriteResults | - ConfigOptions.StopOnFirstError | + ConfigOptions.JoinSummary | + ConfigOptions.KeepBenchmarkFiles | + ConfigOptions.DontOverwriteResults | + ConfigOptions.StopOnFirstError | ConfigOptions.DisableLogFile, "--join", "--keepFiles", "--noOverwrite", "--stopOnFirstError", "--disableLogFile")] [InlineData( ConfigOptions.JoinSummary | @@ -266,7 +266,7 @@ public void PackagesPathParsedCorrectly() Assert.NotNull(toolchain); Assert.Equal(fakeRestoreDirectory, ((DotNetCliGenerator)toolchain.Generator).PackagesPath); } - + [Fact] public void UserCanSpecifyBuildTimeout() { @@ -278,7 +278,7 @@ public void UserCanSpecifyBuildTimeout() Assert.NotNull(toolchain); Assert.Equal(timeoutInSeconds, ((DotNetCliBuilder)toolchain.Builder).Timeout.TotalSeconds); } - + [Fact] public void WhenUserDoesNotSpecifyTimeoutTheDefaultValueIsUsed() { @@ -289,7 +289,7 @@ public void WhenUserDoesNotSpecifyTimeoutTheDefaultValueIsUsed() Assert.NotNull(toolchain); Assert.Equal(NetCoreAppSettings.DefaultBuildTimeout, ((DotNetCliBuilder)toolchain.Builder).Timeout); } - + [Theory] [InlineData("net461")] [InlineData("net462")] @@ -305,7 +305,7 @@ public void NetFrameworkMonikerParsedCorrectly(string tfm) Assert.NotNull(toolchain); Assert.Equal(tfm, ((DotNetCliGenerator)toolchain.Generator).TargetFrameworkMoniker); } - + [Fact] public void CanCompareFewDifferentRuntimes() { @@ -317,7 +317,7 @@ public void CanCompareFewDifferentRuntimes() Assert.Single(config.GetJobs().Where(job => job.Environment.Runtime is CoreRuntime coreRuntime && coreRuntime.MsBuildMoniker == "netcoreapp3.0" && coreRuntime.TargetFrameworkMoniker == TargetFrameworkMoniker.NetCoreApp30)); Assert.Single(config.GetJobs().Where(job => job.Environment.Runtime is CoreRtRuntime coreRtRuntime && coreRtRuntime.MsBuildMoniker == "netcoreapp3.0" && coreRtRuntime.TargetFrameworkMoniker == TargetFrameworkMoniker.CoreRt30)); } - + [Theory] [InlineData(ThresholdUnit.Ratio, 5)] [InlineData(ThresholdUnit.Milliseconds, 10)] @@ -325,10 +325,10 @@ public void CanUseStatisticalTestsToCompareFewDifferentRuntimes(ThresholdUnit th { var config = ConfigParser.Parse(new[] { - "--runtimes", "netcoreapp2.1", "netcoreapp2.2", + "--runtimes", "netcoreapp2.1", "netcoreapp2.2", "--statisticalTest", $"{thresholdValue.ToString(CultureInfo.InvariantCulture)}{thresholdUnit.ToShortName()}" }, new OutputLogger(Output)).config; - + var mockSummary = MockFactory.CreateSummary(config); Assert.True(config.GetJobs().First().Meta.Baseline); // when the user provides multiple runtimes the first one should be marked as baseline @@ -375,11 +375,11 @@ public void TooManyHardwareCounterNameMeansFailure() public void CanParseDisassemblerWithCustomRecursiveDepth() { const int depth = 123; - + var config = ConfigParser.Parse(new[] { "--disasm", "--disasmDepth", depth.ToString()}, new OutputLogger(Output)).config; var diagnoser = config.GetDiagnosers().OfType().Single(); - + Assert.Equal(depth, diagnoser.Config.RecursiveDepth); Assert.True(diagnoser.Config.PrintPrologAndEpilog); // we want this option to be enabled by default for command line users } @@ -399,9 +399,9 @@ public void UserCanSpecifyCustomDefaultJobAndOverwriteItsSettingsViaConsoleArgs( .With(Job.Default .WithWarmupCount(1) .AsDefault()); - + var parserdConfig = ConfigParser.Parse(new[] { "--warmupCount", "2"}, new OutputLogger(Output), globalConfig).config; - + Assert.Equal(2, parserdConfig.GetJobs().Single().Run.WarmupCount); Assert.False(parserdConfig.GetJobs().Single().Meta.IsDefault); // after the merge the job is not "default" anymore } diff --git a/tests/BenchmarkDotNet.Tests/Configs/ConfigOptionsTests.cs b/tests/BenchmarkDotNet.Tests/Configs/ConfigOptionsTests.cs index f38f0ac3ca..b9e6099ca5 100644 --- a/tests/BenchmarkDotNet.Tests/Configs/ConfigOptionsTests.cs +++ b/tests/BenchmarkDotNet.Tests/Configs/ConfigOptionsTests.cs @@ -19,7 +19,7 @@ public class ConfigOptionsTests [Fact] public void DefaultConfigDoesNotDisableLogFile() => Assert.False(DefaultConfig.Instance.Options.HasFlag(ConfigOptions.DisableLogFile)); - + [Fact] public void DefaultConfigDoesDisableOptimizationsValidator() => Assert.False(DefaultConfig.Instance.Options.HasFlag(ConfigOptions.DisableOptimizationsValidator)); diff --git a/tests/BenchmarkDotNet.Tests/Configs/EnvironmentVariableTests.cs b/tests/BenchmarkDotNet.Tests/Configs/EnvironmentVariableTests.cs index d29b3e1b28..48be4c9b03 100644 --- a/tests/BenchmarkDotNet.Tests/Configs/EnvironmentVariableTests.cs +++ b/tests/BenchmarkDotNet.Tests/Configs/EnvironmentVariableTests.cs @@ -44,7 +44,7 @@ public void AddOneVariable() Assert.Equal(new EnvironmentVariable("c", "d"), job.Environment.EnvironmentVariables[1]); Assert.Equal(new EnvironmentVariable("e", "f"), job.Environment.EnvironmentVariables[2]); } - + [Fact] public void OverrideOneVariable() { diff --git a/tests/BenchmarkDotNet.Tests/Configs/JobTests.cs b/tests/BenchmarkDotNet.Tests/Configs/JobTests.cs index 688a111f92..a4d1e31e51 100644 --- a/tests/BenchmarkDotNet.Tests/Configs/JobTests.cs +++ b/tests/BenchmarkDotNet.Tests/Configs/JobTests.cs @@ -252,12 +252,12 @@ public static void PredefinedJobIdIsNotPreserved() Assert.NotEqual(predefinedJob.Id, customJob.Id); } - + [Fact] public static void BaselineDoesntChangeId() { const string id = "theId"; - + var predefinedJob = Job.Default; var customJob = predefinedJob.AsBaseline(); Assert.Equal(predefinedJob.Id, customJob.Id); @@ -399,19 +399,19 @@ public static void Test06CharacteristicHacks() Assert.Throws(() => a[j] = new CharacteristicSet()); // not assignable; Assert.Throws(() => a[j] = 123); // not assignable; } - + [Fact] public static void MutatorAppliedToOtherJobOverwritesOnlyTheConfiguredSettings() { var jobBefore = Job.Default.With(CoreRuntime.Core30); // this is a default job with Runtime set to Core var copy = jobBefore.UnfreezeCopy(); - + Assert.False(copy.HasValue(RunMode.MaxIterationCountCharacteristic)); var mutator = Job.Default.WithMaxIterationCount(20); copy.Apply(mutator); - + Assert.True(copy.HasValue(RunMode.MaxIterationCountCharacteristic)); Assert.Equal(20, copy.Run.MaxIterationCount); Assert.False(jobBefore.HasValue(RunMode.MaxIterationCountCharacteristic)); @@ -441,7 +441,7 @@ public static void AllJobModesPropertyNamesMatchCharacteristicNames() // it's ma } [Fact] - public static void WithNuGet() + public static void WithNuGet() { var j = new Job("SomeId"); @@ -449,7 +449,7 @@ public static void WithNuGet() j = j.Freeze().WithNuGet("Newtonsoft.Json"); Assert.Equal(1, j.Infrastructure.NuGetReferences.Count); - + j = j.WithNuGet("AutoMapper", "7.0.1"); Assert.Collection(j.Infrastructure.NuGetReferences, reference => Assert.Equal(new NuGetReference("AutoMapper", "7.0.1"), reference), @@ -477,7 +477,7 @@ public static void WithNuGet() private static bool IsSubclassOfobModeOfItself(Type type) { Type jobModeOfT; - + try { jobModeOfT = typeof(JobMode<>).MakeGenericType(type); @@ -486,7 +486,7 @@ private static bool IsSubclassOfobModeOfItself(Type type) { return false; } - + return type.IsSubclassOf(jobModeOfT); } } diff --git a/tests/BenchmarkDotNet.Tests/Engine/EngineResultStageTests.cs b/tests/BenchmarkDotNet.Tests/Engine/EngineResultStageTests.cs index 69709cf982..afbd596bad 100644 --- a/tests/BenchmarkDotNet.Tests/Engine/EngineResultStageTests.cs +++ b/tests/BenchmarkDotNet.Tests/Engine/EngineResultStageTests.cs @@ -23,7 +23,7 @@ public void OutliersTest() CheckResults(5, measurements, OutlierMode.RemoveUpper); CheckResults(5, measurements, OutlierMode.RemoveAll); - + CheckResults(6, measurements, OutlierMode.DontRemove); CheckResults(6, measurements, OutlierMode.RemoveLower); } diff --git a/tests/BenchmarkDotNet.Tests/Engine/EngineWarmupStageTests.cs b/tests/BenchmarkDotNet.Tests/Engine/EngineWarmupStageTests.cs index 69fde9a7b9..dc4a167784 100644 --- a/tests/BenchmarkDotNet.Tests/Engine/EngineWarmupStageTests.cs +++ b/tests/BenchmarkDotNet.Tests/Engine/EngineWarmupStageTests.cs @@ -59,20 +59,20 @@ public void AutoTest_WithoutSteadyStateOverhead() public void MinAndMaxWarmupCountAttributesCanForceAutoWarmup() { const int explicitWarmupCount = 1; - + var warmupCountEqualOne = DefaultConfig.Instance.With(Job.Default.WithWarmupCount(explicitWarmupCount)); var benchmarkRunInfo = BenchmarkConverter.TypeToBenchmarks(typeof(WithForceAutoWarmup), warmupCountEqualOne); var mergedJob = benchmarkRunInfo.BenchmarksCases.Single().Job; - + Assert.Equal(EngineResolver.ForceAutoWarmup, mergedJob.Run.WarmupCount); Assert.Equal(2, mergedJob.Run.MinWarmupIterationCount); Assert.Equal(4, mergedJob.Run.MaxWarmupIterationCount); - + AutoTest(data => TimeInterval.Millisecond * (data.Index % 2), 2, 4, job: mergedJob); } - + [MinWarmupCount(2, forceAutoWarmup: true)] [MaxWarmupCount(4, forceAutoWarmup: true)] public class WithForceAutoWarmup diff --git a/tests/BenchmarkDotNet.Tests/Engine/StoppingCriteria/StoppingCriteriaTestsBase.cs b/tests/BenchmarkDotNet.Tests/Engine/StoppingCriteria/StoppingCriteriaTestsBase.cs index 645adcbe7b..39b83da67a 100644 --- a/tests/BenchmarkDotNet.Tests/Engine/StoppingCriteria/StoppingCriteriaTestsBase.cs +++ b/tests/BenchmarkDotNet.Tests/Engine/StoppingCriteria/StoppingCriteriaTestsBase.cs @@ -32,7 +32,7 @@ protected void ResolutionsAreCorrect(IStoppingCriteria criteria, double[] values Assert.Equal(expectedIsFinished, actualIsFinished); } } - + private static IReadOnlyList Generate(params double[] values) { var measurements = new List(values.Length); @@ -44,7 +44,7 @@ private static IReadOnlyList Generate(params double[] values) public class Warnings { public static readonly Warnings Empty = new Warnings(); - + public string[] Messages { get; } public Warnings(params string[] messages) => Messages = messages; diff --git a/tests/BenchmarkDotNet.Tests/Environments/ProcessorBrandStringTests.cs b/tests/BenchmarkDotNet.Tests/Environments/ProcessorBrandStringTests.cs index 5e3a2eff47..0d450a8c03 100644 --- a/tests/BenchmarkDotNet.Tests/Environments/ProcessorBrandStringTests.cs +++ b/tests/BenchmarkDotNet.Tests/Environments/ProcessorBrandStringTests.cs @@ -33,19 +33,19 @@ public void CoreIsPrettifiedWithDiffFrequencies(string originalName, string pret { Assert.Equal(prettifiedName, ProcessorBrandStringHelper.Prettify(new CpuInfo(originalName, nominalFrequency: Frequency.FromGHz(actualFrequency)), includeMaxFrequency: true)); } - + [Theory] [InlineData("AMD Ryzen 7 2700X Eight-Core Processor", "AMD Ryzen 7 2700X 4.10GHz", 4.1, 8, 16)] [InlineData("AMD Ryzen 7 2700X Eight-Core Processor", "AMD Ryzen 7 2700X Eight-Core Processor 4.10GHz", 4.1, null, null)] public void AmdIsPrettifiedWithDiffFrequencies(string originalName, string prettifiedName, double actualFrequency, int? physicalCoreCount, int? logicalCoreCount) { var cpuInfo = new CpuInfo( - originalName, + originalName, physicalProcessorCount: null, - physicalCoreCount, - logicalCoreCount, + physicalCoreCount, + logicalCoreCount, Frequency.FromGHz(actualFrequency), - minFrequency: null, + minFrequency: null, maxFrequency: null); Assert.Equal(prettifiedName, ProcessorBrandStringHelper.Prettify(cpuInfo, includeMaxFrequency: true)); @@ -59,7 +59,7 @@ public void IntelCoreMicroarchitecture(string modelNumber, string microarchitect { Assert.Equal(microarchitecture, ProcessorBrandStringHelper.ParseIntelCoreMicroarchitecture(modelNumber)); } - + [Theory] [InlineData("", "Unknown processor")] [InlineData(null, "Unknown processor")] diff --git a/tests/BenchmarkDotNet.Tests/Exporters/MarkdownExporterApprovalTests.cs b/tests/BenchmarkDotNet.Tests/Exporters/MarkdownExporterApprovalTests.cs index 79ef87d2a1..2d673d7742 100644 --- a/tests/BenchmarkDotNet.Tests/Exporters/MarkdownExporterApprovalTests.cs +++ b/tests/BenchmarkDotNet.Tests/Exporters/MarkdownExporterApprovalTests.cs @@ -48,16 +48,16 @@ public void GroupExporterTest(Type benchmarkType) var logger = new AccumulationLogger(); logger.WriteLine("=== " + benchmarkType.Name + " ==="); - + var exporter = MarkdownExporter.Mock; var summary = MockFactory.CreateSummary(benchmarkType); exporter.ExportToLog(summary, logger); - + var validator = BaselineValidator.FailOnError; var errors = validator.Validate(new ValidationParameters(summary.BenchmarksCases, summary.BenchmarksCases.First().Config)).ToList(); logger.WriteLine(); logger.WriteLine("Errors: " + errors.Count); - foreach (var error in errors) + foreach (var error in errors) logger.WriteLineError("* " + error.Message); Approvals.Verify(logger.GetLog()); @@ -218,9 +218,9 @@ [Benchmark] public void Base() { } [Benchmark] public void Foo() { } [Benchmark] public void Bar() { } } - + /* MethodJobBaseline */ - + [RankColumn, LogicalGroupColumn, BaselineColumn] [SimpleJob(id: "Job1", baseline: true), SimpleJob(id: "Job2")] public class MethodJobBaseline_MethodsJobs @@ -234,11 +234,11 @@ [Benchmark] public void Bar() {} public class MethodJobBaseline_MethodsJobsParams { [Params(2, 10), UsedImplicitly] public int Param; - + [Benchmark(Baseline = true)] public void Foo() {} [Benchmark] public void Bar() {} } - + /* Invalid */ [RankColumn, LogicalGroupColumn, BaselineColumn] @@ -254,7 +254,7 @@ public class Invalid_TwoJobBaselines { [Benchmark] public void Foo() {} [Benchmark] public void Bar() {} - } + } } } } diff --git a/tests/BenchmarkDotNet.Tests/Exporters/XmlSerializerTests.cs b/tests/BenchmarkDotNet.Tests/Exporters/XmlSerializerTests.cs index 557a35ae01..902a6339bd 100644 --- a/tests/BenchmarkDotNet.Tests/Exporters/XmlSerializerTests.cs +++ b/tests/BenchmarkDotNet.Tests/Exporters/XmlSerializerTests.cs @@ -138,7 +138,7 @@ public void WithExcludedPropertyThrowsGivenNameIsNullOrWhiteSpace(string name, T [MemberData(nameof(SerializeTestDataNames))] public void SerializeThrowsGivenNullArguments(string dataName) { - var (writer, source, exception) = SerializeTestDataItems[dataName]; + var (writer, source, exception) = SerializeTestDataItems[dataName]; var serializer = XmlSerializer.GetBuilder(typeof(MockSource)).Build(); Assert.Throws(exception, () => serializer.Serialize(writer, source)); } @@ -163,7 +163,7 @@ public void Deconstruct(out MockXmlWriter writer, out object source, out Type ex exception = Exception; } } - + private static readonly Dictionary SerializeTestDataItems = new Dictionary { {"Null", new SerializeTestData(null, null, typeof(ArgumentNullException))}, diff --git a/tests/BenchmarkDotNet.Tests/FullNameProviderTests.cs b/tests/BenchmarkDotNet.Tests/FullNameProviderTests.cs index 62b2ea5c07..c041eaa312 100644 --- a/tests/BenchmarkDotNet.Tests/FullNameProviderTests.cs +++ b/tests/BenchmarkDotNet.Tests/FullNameProviderTests.cs @@ -22,58 +22,58 @@ private void AssertBenchmarkName(string expectedBenchmarkName) } [Fact] - public void MethodsWithoutArgumentsAreSupported() + public void MethodsWithoutArgumentsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.SimplestCase.Method"); [Fact] public void NestedTypesAreSupported() { - AssertBenchmarkName("BenchmarkDotNet.Tests.Level0+Level1.Method"); // '+' is used for nested types - AssertBenchmarkName("BenchmarkDotNet.Tests.Level0+Level1+Level2.Method"); // '+' is used for nested types - } + AssertBenchmarkName("BenchmarkDotNet.Tests.Level0+Level1.Method"); // '+' is used for nested types + AssertBenchmarkName("BenchmarkDotNet.Tests.Level0+Level1+Level2.Method"); // '+' is used for nested types + } [Fact] - public void IntegerArgumentsAreSupported() + public void IntegerArgumentsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.SingleIntArgument.Method(arg: 1)"); [Fact] - public void CharacterArgumentsAreSupported() + public void CharacterArgumentsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.SingleCharArgument.Method(arg: 'c')"); [Fact] - public void NullArgumentsAreSupported() + public void NullArgumentsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.SingleNullArgument.Method(arg: null)"); // null is just a null (not "null") [Fact] - public void EnumArgumentsAreSupported() + public void EnumArgumentsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.SingleEnumArgument.Method(arg: Read)"); // no enum type name, just value [Fact] - public void MultipleArgumentsAreSupported() + public void MultipleArgumentsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.FewStringArguments.Method(arg1: \"a\", arg2: \"b\", arg3: \"c\", arg4: \"d\")"); [Fact] - public void DateTimeArgumentsAreSupported() + public void DateTimeArgumentsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.SingleDateTimeArgument.Method(arg: 9999-12-31T23:59:59.9999999)"); [Fact] - public void GuidArgumentsAreSupported() + public void GuidArgumentsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.SingleGuidArgument.Method(arg: 00000000-0000-0000-0000-000000000000)"); [Fact] - public void GenericArgumentsAreSupported() + public void GenericArgumentsAreSupported() => AssertBenchmarkName>("BenchmarkDotNet.Tests.SimpleGeneric.Method"); [Fact] - public void ArraysAreSupported() + public void ArraysAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.WithArray.Method(array: [1, 2, 3], value: 4)"); [Fact] - public void UnicodeIsSupported() + public void UnicodeIsSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.WithCrazyUnicodeCharacters.Method(arg1: \"" + "FOO" + "\", arg2: \""+ "\u03C3" + "\", arg3: \"" + "x\u0305" + "\")"); - + [Fact] - public void TabsAndEnters() + public void TabsAndEnters() => AssertBenchmarkName("BenchmarkDotNet.Tests.WithTabAndEnter.Method(tab: \"1\\t2\", enter: \"3\\r\\n4\")"); [Fact] @@ -83,23 +83,23 @@ public void VeryLongArraysAreSupported() [Fact] public void ArraysWithNullsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.WithArrayOfNullStrings.Method(array: [null, null])"); - + [Fact] - public void MultipleParamsAreSupported() + public void MultipleParamsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.WithParameters.Method(Field1: 100, Field2: 200)"); - + [Fact] - public void ArgumentsAndParamsUsedTogetherAreSupported() + public void ArgumentsAndParamsUsedTogetherAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.WithArgumentsAndParameters.Method(arg: \"anArgument\", Field: 100)"); [Fact] public void TypeArgumentsAreWrappedWithTypeofKeywordAndShortTypeNamesAreUsed() => AssertBenchmarkName("BenchmarkDotNet.Tests.WithTypesAsArguments.GetConverter(typeToConvert: typeof(bool), expectedConverter: typeof(System.ComponentModel.BooleanConverter))"); - + [Fact] public void NullableTypesAsArgumentsAreSupported() => AssertBenchmarkName("BenchmarkDotNet.Tests.WithNullableTypeAsArgument.GetConverter(typeToConvert: typeof(BenchmarkDotNet.Tests.SomeValueType?), expectedConverter: typeof(System.ComponentModel.NullableConverter))"); - + [Fact] public void VoidTypeAsArgumentIsTransaltedToSystemDotVoid() => AssertBenchmarkName("BenchmarkDotNet.Tests.WithVoidTypeAsArgument.GetConverter(typeToConvert: typeof(System.Void), expectedConverter: typeof(System.ComponentModel.TypeConverter))"); @@ -214,7 +214,7 @@ public IEnumerable Data() yield return new object[] { "FOO", "\u03C3", "x\u0305" }; // https://github.com/Microsoft/xunit-performance/blob/f1d1d62a934694d8cd19063e60e04c590711d904/tests/simpleharness/Program.cs#L29 } } - + public class WithTabAndEnter { [Benchmark] @@ -250,14 +250,14 @@ public class WithParameters { [Params(100)] public int Field1; - + [Params(200)] public int Field2; [Benchmark] public int Method() => Field1 + Field2; } - + public class WithArgumentsAndParameters { [Params(100)] @@ -267,7 +267,7 @@ public class WithArgumentsAndParameters [Arguments("anArgument")] public int Method(string arg) => Field; } - + public class WithTypesAsArguments { [Benchmark] @@ -281,7 +281,7 @@ public class WithNullableTypeAsArgument [Arguments(typeof(SomeValueType?), typeof(NullableConverter))] public TypeConverter GetConverter(Type typeToConvert, Type expectedConverter) => TypeDescriptor.GetConverter(typeToConvert); } - + public struct SomeValueType { } public class WithVoidTypeAsArgument diff --git a/tests/BenchmarkDotNet.Tests/GenericBuilderTests.cs b/tests/BenchmarkDotNet.Tests/GenericBuilderTests.cs index f29608fcb8..c48e76d9af 100644 --- a/tests/BenchmarkDotNet.Tests/GenericBuilderTests.cs +++ b/tests/BenchmarkDotNet.Tests/GenericBuilderTests.cs @@ -11,29 +11,29 @@ public class GenericBuilderTests public void TestBuildGenericWithOneArgument() { var types = GenericBenchmarksBuilder.GetRunnableBenchmarks(new [] {typeof(OneArgGenericBenchmark<>)}); - + Assert.Equal(2, types.Length); Assert.Single(types, typeof(OneArgGenericBenchmark)); Assert.Single(types, typeof(OneArgGenericBenchmark)); } - + [GenericTypeArguments(typeof(int))] [GenericTypeArguments(typeof(char))] public class OneArgGenericBenchmark { [Benchmark] public T CreateT() => Activator.CreateInstance(); } - + [Fact] public void TestBuildGenericWithTwoArguments() { var types = GenericBenchmarksBuilder.GetRunnableBenchmarks(new [] {typeof(TwoArgGenericBenchmark<,>)}); - + Assert.Equal(2, types.Length); Assert.Single(types, typeof(TwoArgGenericBenchmark)); Assert.Single(types, typeof(TwoArgGenericBenchmark)); } - + [GenericTypeArguments(typeof(int), typeof(char))] [GenericTypeArguments(typeof(char), typeof(string))] public class TwoArgGenericBenchmark @@ -42,17 +42,17 @@ public class TwoArgGenericBenchmark [Benchmark] public T2 CreateT2() => Activator.CreateInstance(); } - + [Fact] public void TestBuildGenericWithThreeArguments() { var types = GenericBenchmarksBuilder.GetRunnableBenchmarks(new [] {typeof(ThreeArgGenericBenchmark<,,>)}); - + Assert.Equal(2, types.Length); Assert.Single(types, typeof(ThreeArgGenericBenchmark)); Assert.Single(types, typeof(ThreeArgGenericBenchmark)); } - + [GenericTypeArguments(typeof(int), typeof(char), typeof(string))] [GenericTypeArguments(typeof(char), typeof(string), typeof(byte))] public class ThreeArgGenericBenchmark @@ -60,20 +60,20 @@ public class ThreeArgGenericBenchmark [Benchmark] public T1 CreateT1() => Activator.CreateInstance(); [Benchmark] public T2 CreateT2() => Activator.CreateInstance(); - + [Benchmark] public T3 CreateT3() => Activator.CreateInstance(); } - + [Fact] public void TestBuildGenericWithWrongAttributes() { var types = GenericBenchmarksBuilder.GetRunnableBenchmarks(new [] {typeof(GenericBenchmarkWithWrongAttribute<,>)}); - + Assert.Equal(2, types.Length); Assert.Single(types, typeof(GenericBenchmarkWithWrongAttribute)); Assert.Single(types, typeof(GenericBenchmarkWithWrongAttribute)); } - + [GenericTypeArguments(typeof(int), typeof(char))] [GenericTypeArguments(typeof(char), typeof(string))] [GenericTypeArguments(typeof(char))] @@ -83,40 +83,40 @@ public class GenericBenchmarkWithWrongAttribute [Benchmark] public T2 CreateT2() => Activator.CreateInstance(); } - + [Fact] public void TestBuildGenericWithConstraints() { var types = GenericBenchmarksBuilder.GetRunnableBenchmarks(new [] {typeof(GenericBenchmarkWithConstraints<,>)}); - + Assert.Equal(2, types.Length); Assert.Single(types, typeof(GenericBenchmarkWithConstraints)); Assert.Single(types, typeof(GenericBenchmarkWithConstraints)); } - + [GenericTypeArguments(typeof(int), typeof(char))] [GenericTypeArguments(typeof(char), typeof(byte))] public class GenericBenchmarkWithConstraints where T1 : struct - where T2 : struct + where T2 : struct { [Benchmark] public T1 CreateT1() => Activator.CreateInstance(); [Benchmark] public T2 CreateT2() => Activator.CreateInstance(); } - + [Fact] public void TestBuildGenericWithConstraintsWrongArgs() { var types = GenericBenchmarksBuilder.GetRunnableBenchmarks(new [] {typeof(GenericBenchmarkWithConstraintsWrongArgs<,>)}); - + Assert.Single(types); Assert.Single(types, typeof(GenericBenchmarkWithConstraintsWrongArgs)); } - + [GenericTypeArguments(typeof(int), typeof(char))] [GenericTypeArguments(typeof(char), typeof(string))] public class GenericBenchmarkWithConstraintsWrongArgs where T1 : struct - where T2 : struct + where T2 : struct { [Benchmark] public T1 CreateT1() => Activator.CreateInstance(); diff --git a/tests/BenchmarkDotNet.Tests/LevenshteinDistanceCalculatorTests.cs b/tests/BenchmarkDotNet.Tests/LevenshteinDistanceCalculatorTests.cs index c3bab884b6..e9184d3b63 100644 --- a/tests/BenchmarkDotNet.Tests/LevenshteinDistanceCalculatorTests.cs +++ b/tests/BenchmarkDotNet.Tests/LevenshteinDistanceCalculatorTests.cs @@ -6,36 +6,36 @@ namespace BenchmarkDotNet.Tests public class LevenshteinDistanceCalculatorTests { private readonly LevenshteinDistanceCalculator calculator; - + public LevenshteinDistanceCalculatorTests() { calculator = new LevenshteinDistanceCalculator(); } - + [Fact] public void EmptyEmpty() { Assert.Equal(0, calculator.Calculate("", "")); } - + [Fact] public void SelfSelf() { Assert.Equal(0, calculator.Calculate("string", "string")); } - + [Fact] public void TheOnlyDifference() { Assert.Equal(1, calculator.Calculate("strng", "string")); } - + [Fact] public void AllDifferences() { Assert.Equal(5, calculator.Calculate("abcde", "fghij")); } - + [Fact] public void EmptyString() { diff --git a/tests/BenchmarkDotNet.Tests/Loggers/LoggerWithPrefixTests.cs b/tests/BenchmarkDotNet.Tests/Loggers/LoggerWithPrefixTests.cs index 4af0d8f138..2fd5afc612 100644 --- a/tests/BenchmarkDotNet.Tests/Loggers/LoggerWithPrefixTests.cs +++ b/tests/BenchmarkDotNet.Tests/Loggers/LoggerWithPrefixTests.cs @@ -9,7 +9,7 @@ public class LoggerWithPrefixTests { private readonly LoggerWithPrefix loggerWithPrefix; private readonly AccumulationLogger logger; - + public LoggerWithPrefixTests() { logger = new AccumulationLogger(); @@ -23,7 +23,7 @@ public void Write() loggerWithPrefix.Write("2"); Assert.Equal("prefix12", logger.GetLog()); } - + [Fact] public void WriteLine() { @@ -31,7 +31,7 @@ public void WriteLine() loggerWithPrefix.WriteLine("2"); Assert.Equal($"prefix1{Environment.NewLine}prefix2{Environment.NewLine}", logger.GetLog()); } - + [Fact] public void Write_EmptyLine() { @@ -39,7 +39,7 @@ public void Write_EmptyLine() loggerWithPrefix.Write(string.Empty); Assert.Equal(string.Empty, logger.GetLog()); } - + [Fact] public void WriteLine_EmptyLine() { @@ -47,7 +47,7 @@ public void WriteLine_EmptyLine() loggerWithPrefix.WriteLine(string.Empty); Assert.Equal($"{Environment.NewLine}{Environment.NewLine}", logger.GetLog()); } - + [Fact] public void WriteLineWithoutArg() { @@ -62,35 +62,35 @@ public void Write_StringWithOneNewLine() loggerWithPrefix.Write($"1{Environment.NewLine}2"); Assert.Equal($"prefix1{Environment.NewLine}prefix2", logger.GetLog()); } - + [Fact] public void WriteLine_StringWithNewLine() { loggerWithPrefix.WriteLine($"1{Environment.NewLine}2"); Assert.Equal($"prefix1{Environment.NewLine}prefix2{Environment.NewLine}", logger.GetLog()); } - + [Fact] public void Write_StringWithMultipleNewLine() { loggerWithPrefix.Write($"1{Environment.NewLine}2{Environment.NewLine}3"); Assert.Equal($"prefix1{Environment.NewLine}prefix2{Environment.NewLine}prefix3", logger.GetLog()); } - + [Fact] public void WriteLine_StringWithMultipleNewLine() { loggerWithPrefix.WriteLine($"1{Environment.NewLine}2{Environment.NewLine}3"); Assert.Equal($"prefix1{Environment.NewLine}prefix2{Environment.NewLine}prefix3{Environment.NewLine}", logger.GetLog()); } - + [Fact] public void Write_StringWithEmptyNewLine() { loggerWithPrefix.Write($"1{Environment.NewLine}{Environment.NewLine}2"); Assert.Equal($"prefix1{Environment.NewLine}{Environment.NewLine}prefix2", logger.GetLog()); } - + [Fact] public void WriteLine_StringWithEmptyNewLine() { diff --git a/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/AdaptiveHistogramTests.cs b/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/AdaptiveHistogramTests.cs index 6de2b86feb..6ff7fd9c04 100644 --- a/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/AdaptiveHistogramTests.cs +++ b/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/AdaptiveHistogramTests.cs @@ -295,7 +295,7 @@ public void Issue802() }; HistogramTestHelper.DoHistogramTest(output, HistogramBuilder.Adaptive, values, 0.0001, new[] { values }); } - + /// /// /// diff --git a/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/HistogramTestHelper.cs b/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/HistogramTestHelper.cs index 4f31428135..4f834bd125 100644 --- a/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/HistogramTestHelper.cs +++ b/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/HistogramTestHelper.cs @@ -25,7 +25,7 @@ public static void DoHistogramTest([NotNull] ITestOutputHelper output, [NotNull] var actualHistogram = builder.BuildWithFixedBinSize(values, binSize); Check(output, bins, actualHistogram); } - + [AssertionMethod] public static void DoHistogramTest([NotNull] ITestOutputHelper output, [NotNull] IHistogramBuilder builder, [NotNull] double[] values, [NotNull] bool[] states) @@ -45,7 +45,7 @@ private static void Check([NotNull] ITestOutputHelper output, [NotNull] double[] for (int i = 0; i < actualHistogram.Bins.Length; i++) Assert.Equal(expectedBins[i], actualHistogram.Bins[i].Values); } - + [AssertionMethod] private static void Check([NotNull] ITestOutputHelper output, [NotNull] bool[] expectedStates, Histogram actualHistogram) { diff --git a/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/HistogramTests.cs b/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/HistogramTests.cs index dd030c233d..e9c427ded4 100644 --- a/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/HistogramTests.cs +++ b/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/HistogramTests.cs @@ -84,7 +84,7 @@ private void PrintHistogram(string title, Histogram histogram) output.WriteLine($"=== {title}:Full ==="); output.WriteLine(histogram.ToTimeStr(full: true)); } - + [Theory] [InlineData(new[] { 1.0, 2.0, 3.0 })] [InlineData(new[] { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 })] diff --git a/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/MultimodalTests.cs b/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/MultimodalTests.cs index 8df6cc422b..7372a01626 100644 --- a/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/MultimodalTests.cs +++ b/tests/BenchmarkDotNet.Tests/Mathematics/Histograms/MultimodalTests.cs @@ -38,7 +38,7 @@ public void RandomTest() var values = new double[n]; for (int i = 0; i < n; i++) values[i] = random.NextGaussian(50, 3); - + var s = new Statistics(values); var histogram = HistogramBuilder.Adaptive.Build(s); output.Print($"n={n}", histogram); diff --git a/tests/BenchmarkDotNet.Tests/Mathematics/StatisticalTesting/MannWhitneyTests.cs b/tests/BenchmarkDotNet.Tests/Mathematics/StatisticalTesting/MannWhitneyTests.cs index 0f7090bffe..801c7c11b5 100644 --- a/tests/BenchmarkDotNet.Tests/Mathematics/StatisticalTesting/MannWhitneyTests.cs +++ b/tests/BenchmarkDotNet.Tests/Mathematics/StatisticalTesting/MannWhitneyTests.cs @@ -126,23 +126,23 @@ public void N3Vs49(double t, int u, double pValue) }; double[] y = { - 12.3709584471467, 10.4353018286039, 11.3631284113373, 11.632862604961, - 11.404268323141, 10.8938754839085, 12.5115219974389, 10.9053409615869, - 13.018423713877, 10.9372859009476, 12.3048696542235, 13.2866453927011, - 9.61113929888766, 10.7212112331826, 10.8666786636063, 11.6359503980701, - 10.7157470785839, 8.34354457909522, 8.55953307142448, 12.3201133457302, - 10.6933614059215, 9.21869156602, 10.8280826442404, 12.2146746991726, - 12.895193461265, 10.5695308683938, 10.7427306172311, 9.23683691480522, - 11.4600973548313, 10.3600051240399, 11.4554501232412, 11.7048373372288, - 12.0351035219699, 10.3910736245928, 11.504955123298, 9.28299132092666, - 10.2155409916205, 10.1490924058235, 8.58579235005337, 11.0361226068923, - 11.2059986002003, 10.6389427014513, 11.7581632356995, 10.2732951729234, - 9.63171895558071, 11.4328180258887, 10.1886068238133, 12.4441012617213, + 12.3709584471467, 10.4353018286039, 11.3631284113373, 11.632862604961, + 11.404268323141, 10.8938754839085, 12.5115219974389, 10.9053409615869, + 13.018423713877, 10.9372859009476, 12.3048696542235, 13.2866453927011, + 9.61113929888766, 10.7212112331826, 10.8666786636063, 11.6359503980701, + 10.7157470785839, 8.34354457909522, 8.55953307142448, 12.3201133457302, + 10.6933614059215, 9.21869156602, 10.8280826442404, 12.2146746991726, + 12.895193461265, 10.5695308683938, 10.7427306172311, 9.23683691480522, + 11.4600973548313, 10.3600051240399, 11.4554501232412, 11.7048373372288, + 12.0351035219699, 10.3910736245928, 11.504955123298, 9.28299132092666, + 10.2155409916205, 10.1490924058235, 8.58579235005337, 11.0361226068923, + 11.2059986002003, 10.6389427014513, 11.7581632356995, 10.2732951729234, + 9.63171895558071, 11.4328180258887, 10.1886068238133, 12.4441012617213, 10.5685537973867 }; Check(x, y, new AbsoluteThreshold(t), u, pValue); } - + [Theory] [InlineData(0, 61, 0.8373)] public void N3Vs62(double t, int u, double pValue) @@ -155,21 +155,21 @@ public void N3Vs62(double t, int u, double pValue) }; double[] y = { - 12.3709584471467, 10.4353018286039, 11.3631284113373, 11.632862604961, - 11.404268323141, 10.8938754839085, 12.5115219974389, 10.9053409615869, - 13.018423713877, 10.9372859009476, 12.3048696542235, 13.2866453927011, - 9.61113929888766, 10.7212112331826, 10.8666786636063, 11.6359503980701, - 10.7157470785839, 8.34354457909522, 8.55953307142448, 12.3201133457302, - 10.6933614059215, 9.21869156602, 10.8280826442404, 12.2146746991726, - 12.895193461265, 10.5695308683938, 10.7427306172311, 9.23683691480522, - 11.4600973548313, 10.3600051240399, 11.4554501232412, 11.7048373372288, - 12.0351035219699, 10.3910736245928, 11.504955123298, 9.28299132092666, - 10.2155409916205, 10.1490924058235, 8.58579235005337, 11.0361226068923, - 11.2059986002003, 10.6389427014513, 11.7581632356995, 10.2732951729234, - 9.63171895558071, 11.4328180258887, 10.1886068238133, 12.4441012617213, - 10.5685537973867, 11.6556478834022, 11.3219252652039, 10.2161610591196, - 12.575727519792, 11.6428993057173, 11.0897606465996, 11.2765507472915, - 11.6792888160553, 11.0898328865791, 8.00690991684706, 11.2848829535307, + 12.3709584471467, 10.4353018286039, 11.3631284113373, 11.632862604961, + 11.404268323141, 10.8938754839085, 12.5115219974389, 10.9053409615869, + 13.018423713877, 10.9372859009476, 12.3048696542235, 13.2866453927011, + 9.61113929888766, 10.7212112331826, 10.8666786636063, 11.6359503980701, + 10.7157470785839, 8.34354457909522, 8.55953307142448, 12.3201133457302, + 10.6933614059215, 9.21869156602, 10.8280826442404, 12.2146746991726, + 12.895193461265, 10.5695308683938, 10.7427306172311, 9.23683691480522, + 11.4600973548313, 10.3600051240399, 11.4554501232412, 11.7048373372288, + 12.0351035219699, 10.3910736245928, 11.504955123298, 9.28299132092666, + 10.2155409916205, 10.1490924058235, 8.58579235005337, 11.0361226068923, + 11.2059986002003, 10.6389427014513, 11.7581632356995, 10.2732951729234, + 9.63171895558071, 11.4328180258887, 10.1886068238133, 12.4441012617213, + 10.5685537973867, 11.6556478834022, 11.3219252652039, 10.2161610591196, + 12.575727519792, 11.6428993057173, 11.0897606465996, 11.2765507472915, + 11.6792888160553, 11.0898328865791, 8.00690991684706, 11.2848829535307, 10.632765357259, 11.1852305648656 }; Check(x, y, new AbsoluteThreshold(t), u, pValue); diff --git a/tests/BenchmarkDotNet.Tests/Mathematics/StatisticalTesting/StudentTests.cs b/tests/BenchmarkDotNet.Tests/Mathematics/StatisticalTesting/StudentTests.cs index dc4c6d6c02..74bdd6af41 100644 --- a/tests/BenchmarkDotNet.Tests/Mathematics/StatisticalTesting/StudentTests.cs +++ b/tests/BenchmarkDotNet.Tests/Mathematics/StatisticalTesting/StudentTests.cs @@ -9,7 +9,7 @@ namespace BenchmarkDotNet.Tests.Mathematics.StatisticalTesting public class StudentTests { private readonly ITestOutputHelper output; - + public StudentTests(ITestOutputHelper output) => this.output = output; [Fact] @@ -87,7 +87,7 @@ public void Student300Test() Check(x, 100, 0.6487); Check(x, 101, 1); } - + [AssertionMethod] private void Check(double[] x, double y, double pvalue) { diff --git a/tests/BenchmarkDotNet.Tests/Mocks/MockEngine.cs b/tests/BenchmarkDotNet.Tests/Mocks/MockEngine.cs index 1cb6301e31..16db542bc2 100644 --- a/tests/BenchmarkDotNet.Tests/Mocks/MockEngine.cs +++ b/tests/BenchmarkDotNet.Tests/Mocks/MockEngine.cs @@ -22,7 +22,7 @@ public MockEngine(ITestOutputHelper output, Job job, Func GlobalSetupAction?.Invoke(); [UsedImplicitly] diff --git a/tests/BenchmarkDotNet.Tests/Mocks/MockFactory.cs b/tests/BenchmarkDotNet.Tests/Mocks/MockFactory.cs index 759ecff6e6..a100b98561 100644 --- a/tests/BenchmarkDotNet.Tests/Mocks/MockFactory.cs +++ b/tests/BenchmarkDotNet.Tests/Mocks/MockFactory.cs @@ -50,10 +50,10 @@ public static Summary CreateSummary(IConfig config, bool hugeSd, Metric[] metric TimeSpan.FromMinutes(1), ImmutableArray.Empty); - private static ImmutableArray CreateReports(IConfig config) + private static ImmutableArray CreateReports(IConfig config) => CreateBenchmarks(config).Select(CreateSimpleReport).ToImmutableArray(); - private static BenchmarkCase[] CreateBenchmarks(IConfig config) + private static BenchmarkCase[] CreateBenchmarks(IConfig config) => BenchmarkConverter.TypeToBenchmarks(typeof(TBenchmarks), config).BenchmarksCases; private static BenchmarkReport CreateSimpleReport(BenchmarkCase benchmarkCase) => CreateReport(benchmarkCase, 1, 1); diff --git a/tests/BenchmarkDotNet.Tests/MonoDisassemblyOutputParserTests.cs b/tests/BenchmarkDotNet.Tests/MonoDisassemblyOutputParserTests.cs index e2f30000a0..d8fa25694f 100644 --- a/tests/BenchmarkDotNet.Tests/MonoDisassemblyOutputParserTests.cs +++ b/tests/BenchmarkDotNet.Tests/MonoDisassemblyOutputParserTests.cs @@ -241,7 +241,7 @@ operable program or batch file. Check(input, expected, "Foo"); } - + [Fact] public void CanParseInvalidMonoDisassemblyOutput() { @@ -289,7 +289,7 @@ private static void Check(string input, DisassemblyResult expected, string metho for (int i = 0; i < expected.Methods[0].Maps[0].Instructions.Length; i++) Assert.Equal(expected.Methods[0].Maps[0].Instructions[i].TextRepresentation, disassemblyResult.Methods[0].Maps[0].Instructions[i].TextRepresentation); - + Assert.Equal(expected.Errors.Length, disassemblyResult.Errors.Length); for (int i = 0; i < expected.Errors.Length; i++) Assert.Equal(expected.Errors[i].Replace("\r", "").Replace("\n", ""), disassemblyResult.Errors[i].Replace("\r", "").Replace("\n", "")); diff --git a/tests/BenchmarkDotNet.Tests/MultiEncodingStringTests.cs b/tests/BenchmarkDotNet.Tests/MultiEncodingStringTests.cs index 1e5f288cbd..c77cd1d0c2 100644 --- a/tests/BenchmarkDotNet.Tests/MultiEncodingStringTests.cs +++ b/tests/BenchmarkDotNet.Tests/MultiEncodingStringTests.cs @@ -12,13 +12,13 @@ public void TestEquals() { var enc1 = Encoding.ASCII; var enc2 = Encoding.Unicode; - + Assert.Equal(new MultiEncodingString("string", "otherString"), new MultiEncodingString("string", "otherString")); Assert.Equal(new MultiEncodingString("string", "otherString").GetHashCode(), new MultiEncodingString("string", "otherString").GetHashCode()); - + Assert.NotEqual(new MultiEncodingString(new[] {new KeyValuePair(enc1,"string")}), new MultiEncodingString(new[] {new KeyValuePair(enc2,"string")})); - + Assert.NotEqual(new MultiEncodingString(new[] {new KeyValuePair(enc1,"string")}).GetHashCode(), new MultiEncodingString(new[] {new KeyValuePair(enc2,"string")}).GetHashCode()); } @@ -32,10 +32,10 @@ public void TestToString() var mes = new MultiEncodingString("string", "otherString"); var otherMes = new MultiEncodingString(new[] { new KeyValuePair(enc1, "string"), new KeyValuePair(enc2, "otherString") }); - + Assert.Equal("string", mes.ToString(enc1)); Assert.Equal("otherString", mes.ToString(enc2)); - + Assert.Equal("string", otherMes.ToString(enc1)); Assert.Equal("otherString", otherMes.ToString(enc2)); } diff --git a/tests/BenchmarkDotNet.Tests/ParameterInstanceTests.cs b/tests/BenchmarkDotNet.Tests/ParameterInstanceTests.cs index 20dc58bd48..a53f40454b 100644 --- a/tests/BenchmarkDotNet.Tests/ParameterInstanceTests.cs +++ b/tests/BenchmarkDotNet.Tests/ParameterInstanceTests.cs @@ -43,7 +43,7 @@ public void VeryLongParameterValuesAreTrimmed(string initialLongText, string exp public void TrimmingTheValuesMakesThemActuallyShorter(string initialLongText, string expectedDisplayText) { var parameter = new ParameterInstance(definition, initialLongText); - + Assert.Equal(expectedDisplayText, parameter.ToDisplayText()); } @@ -59,6 +59,6 @@ public void TypeParameterValuesDisplayNotTrimmedTypeNameWithoutNamespace(Type ty Assert.Equal(expectedName, parameter.ToDisplayText()); } } - + public class ATypeWithAVeryVeryVeryVeryVeryVeryLongNameeeeeeeee { } } diff --git a/tests/BenchmarkDotNet.Tests/Portability/Cpu/ProcCpuInfoParserTests.cs b/tests/BenchmarkDotNet.Tests/Portability/Cpu/ProcCpuInfoParserTests.cs index 78138380d6..264593b44f 100644 --- a/tests/BenchmarkDotNet.Tests/Portability/Cpu/ProcCpuInfoParserTests.cs +++ b/tests/BenchmarkDotNet.Tests/Portability/Cpu/ProcCpuInfoParserTests.cs @@ -16,7 +16,7 @@ public void EmptyTest() Assert.Null(parser.PhysicalCoreCount); Assert.Null(parser.LogicalCoreCount); Assert.Null(parser.NominalFrequency); - + Assert.Null(parser.MaxFrequency); Assert.Null(parser.MinFrequency); } diff --git a/tests/BenchmarkDotNet.Tests/Portability/Cpu/TestHelper.cs b/tests/BenchmarkDotNet.Tests/Portability/Cpu/TestHelper.cs index cd37a55826..e4af5025c0 100644 --- a/tests/BenchmarkDotNet.Tests/Portability/Cpu/TestHelper.cs +++ b/tests/BenchmarkDotNet.Tests/Portability/Cpu/TestHelper.cs @@ -15,6 +15,6 @@ public static string ReadTestFile(string name) { return reader.ReadToEnd(); } - } + } } } \ No newline at end of file diff --git a/tests/BenchmarkDotNet.Tests/ReflectionTests.cs b/tests/BenchmarkDotNet.Tests/ReflectionTests.cs index 385310c684..573620a6e6 100644 --- a/tests/BenchmarkDotNet.Tests/ReflectionTests.cs +++ b/tests/BenchmarkDotNet.Tests/ReflectionTests.cs @@ -91,7 +91,7 @@ private GenericNoPublicCtor() { } [Benchmark] public T Create() => default; } - + [FactDotNetCore21Only("the implicit cast operator is available only in .NET Core 2.1+ (See https://github.com/dotnet/corefx/issues/30121 for more)")] public void StringCanBeUsedAsReadOnlySpanOfCharArgument() => Assert.True(typeof(ReadOnlySpan).IsStackOnlyWithImplicitCast("a string")); diff --git a/tests/BenchmarkDotNet.Tests/Reports/DefaultColumnProvidersTests.cs b/tests/BenchmarkDotNet.Tests/Reports/DefaultColumnProvidersTests.cs index c085d2794c..7f6964bc82 100644 --- a/tests/BenchmarkDotNet.Tests/Reports/DefaultColumnProvidersTests.cs +++ b/tests/BenchmarkDotNet.Tests/Reports/DefaultColumnProvidersTests.cs @@ -33,7 +33,7 @@ public void DefaultStatisticsColumnsTest(bool hugeSd, string expectedColumnNames output.WriteLine("DefaultStatisticsColumns: " + columnNames); Assert.Equal(expectedColumnNames, columnNames); } - + [Fact] public void EveyMetricHasItsOwnColumn() { @@ -41,7 +41,7 @@ public void EveyMetricHasItsOwnColumn() var summary = CreateSummary(false, metrics); var columns = DefaultColumnProviders.Metrics.GetColumns(summary).ToArray(); - + Assert.Equal("metric1", columns[0].Id); Assert.Equal("metric2", columns[1].Id); } diff --git a/tests/BenchmarkDotNet.Tests/Reports/DisplayPrecisionManagerTests.cs b/tests/BenchmarkDotNet.Tests/Reports/DisplayPrecisionManagerTests.cs index 33eebcc9fd..90f994884b 100644 --- a/tests/BenchmarkDotNet.Tests/Reports/DisplayPrecisionManagerTests.cs +++ b/tests/BenchmarkDotNet.Tests/Reports/DisplayPrecisionManagerTests.cs @@ -89,7 +89,7 @@ public void GeneralTest(string testDataName) Assert.Equal(expectedPrecision, actualPrecision); } } - + [Theory] [InlineData(4, 0.01)] [InlineData(4, 0.123456)] diff --git a/tests/BenchmarkDotNet.Tests/Reports/SummaryTableTests.cs b/tests/BenchmarkDotNet.Tests/Reports/SummaryTableTests.cs index ade7f45341..e8ea51a2e6 100644 --- a/tests/BenchmarkDotNet.Tests/Reports/SummaryTableTests.cs +++ b/tests/BenchmarkDotNet.Tests/Reports/SummaryTableTests.cs @@ -71,7 +71,7 @@ public void CustomOrdererIsSupported() var config = ManualConfig.Create(DefaultConfig.Instance); config.Orderer = new DefaultOrderer(SummaryOrderPolicy.FastestToSlowest, MethodOrderPolicy.Alphabetical); var summary = MockFactory.CreateSummary(config); - Assert.True(summary.Orderer is DefaultOrderer defaultOrderer && + Assert.True(summary.Orderer is DefaultOrderer defaultOrderer && defaultOrderer.SummaryOrderPolicy == SummaryOrderPolicy.FastestToSlowest && defaultOrderer.MethodOrderPolicy == MethodOrderPolicy.Alphabetical); } diff --git a/tests/BenchmarkDotNet.Tests/Running/BenchmarkConverterTests.cs b/tests/BenchmarkDotNet.Tests/Running/BenchmarkConverterTests.cs index 89da0ea963..bf42f8ca7a 100644 --- a/tests/BenchmarkDotNet.Tests/Running/BenchmarkConverterTests.cs +++ b/tests/BenchmarkDotNet.Tests/Running/BenchmarkConverterTests.cs @@ -79,7 +79,7 @@ public override void Cleanup() public void IfIterationSetupIsProvidedTheBenchmarkShouldRunOncePerIteration() { var benchmark = BenchmarkConverter.TypeToBenchmarks(typeof(Derived)).BenchmarksCases.Single(); - + Assert.Equal(1, benchmark.Job.Run.InvocationCount); Assert.Equal(1, benchmark.Job.Run.UnrollFactor); } @@ -88,7 +88,7 @@ public void IfIterationSetupIsProvidedTheBenchmarkShouldRunOncePerIteration() public void IfIterationCleanupIsProvidedTheBenchmarkShouldRunOncePerIteration() { var benchmark = BenchmarkConverter.TypeToBenchmarks(typeof(WithIterationCleanupOnly)).BenchmarksCases.Single(); - + Assert.Equal(1, benchmark.Job.Run.InvocationCount); Assert.Equal(1, benchmark.Job.Run.UnrollFactor); } @@ -98,31 +98,31 @@ public class WithIterationCleanupOnly [IterationCleanup] public void Cleanup() { } [Benchmark] public void Benchmark() { } } - + [Fact] public void InvocationCountIsRespectedForBenchmarksWithIterationSetup() { const int InvocationCount = 100; - - var benchmark = BenchmarkConverter.TypeToBenchmarks(typeof(Derived), + + var benchmark = BenchmarkConverter.TypeToBenchmarks(typeof(Derived), DefaultConfig.Instance.With(Job.Default .WithInvocationCount(InvocationCount))) .BenchmarksCases.Single(); - + Assert.Equal(InvocationCount, benchmark.Job.Run.InvocationCount); Assert.NotNull(benchmark.Descriptor.IterationSetupMethod); } - + [Fact] public void UnrollFactorIsRespectedForBenchmarksWithIterationSetup() { const int UnrollFactor = 13; - - var benchmark = BenchmarkConverter.TypeToBenchmarks(typeof(Derived), + + var benchmark = BenchmarkConverter.TypeToBenchmarks(typeof(Derived), DefaultConfig.Instance.With(Job.Default .WithUnrollFactor(UnrollFactor))) .BenchmarksCases.Single(); - + Assert.Equal(UnrollFactor, benchmark.Job.Run.UnrollFactor); Assert.NotNull(benchmark.Descriptor.IterationSetupMethod); } @@ -148,25 +148,25 @@ public class WithMutator { [Benchmark] public void Method() { } } - + [Fact] public void JobMutatorsApplySettingsToDefaultJobIfNoneOfTheConfigsContainsJob() { var info = BenchmarkConverter.TypeToBenchmarks(typeof(WithMutator)); - + var benchmark = info.BenchmarksCases.Single(); - + Assert.Equal(int.MaxValue, benchmark.Job.Run.MaxIterationCount); Assert.False(benchmark.Job.Meta.IsMutator); } - + [Fact] public void OrderOfAppliedAttributesDoesNotAffectMutators() { var info = BenchmarkConverter.TypeToBenchmarks(typeof(WithMutatorAfterJobAttribute)); - + var benchmark = info.BenchmarksCases.Single(); - + Assert.Equal(int.MaxValue, benchmark.Job.Run.MaxIterationCount); Assert.True(benchmark.Job.Environment.Runtime is CoreRuntime); Assert.False(benchmark.Job.Meta.IsMutator); @@ -178,14 +178,14 @@ public class WithMutatorAfterJobAttribute { [Benchmark] public void Method() { } } - + [Fact] public void FewMutatorsCanBeAppliedToSameType() { var info = BenchmarkConverter.TypeToBenchmarks(typeof(WithFewMutators)); - + var benchmarkCase = info.BenchmarksCases.Single(); - + Assert.Equal(1, benchmarkCase.Job.Run.InvocationCount); Assert.Equal(1, benchmarkCase.Job.Run.UnrollFactor); Assert.Equal(OutlierMode.DontRemove, benchmarkCase.Job.Accuracy.OutlierMode); diff --git a/tests/BenchmarkDotNet.Tests/Running/JobRuntimePropertiesComparerTests.cs b/tests/BenchmarkDotNet.Tests/Running/JobRuntimePropertiesComparerTests.cs index 50ec124f8d..9d13d61a0a 100644 --- a/tests/BenchmarkDotNet.Tests/Running/JobRuntimePropertiesComparerTests.cs +++ b/tests/BenchmarkDotNet.Tests/Running/JobRuntimePropertiesComparerTests.cs @@ -95,7 +95,7 @@ public void CustomNuGetJobsWithSamePackageVersionAreGroupedTogether() var config = ManualConfig.Create(DefaultConfig.Instance) .With(job1) .With(job2); - + var benchmarks1 = BenchmarkConverter.TypeToBenchmarks(typeof(Plain1), config); var benchmarks2 = BenchmarkConverter.TypeToBenchmarks(typeof(Plain2), config); diff --git a/tests/BenchmarkDotNet.Tests/SourceCodeHelperTests.cs b/tests/BenchmarkDotNet.Tests/SourceCodeHelperTests.cs index 67c78fd92b..63ce50d7e6 100644 --- a/tests/BenchmarkDotNet.Tests/SourceCodeHelperTests.cs +++ b/tests/BenchmarkDotNet.Tests/SourceCodeHelperTests.cs @@ -22,7 +22,7 @@ public class SourceCodeHelperTests [InlineData('a', "'a'")] [InlineData('\\', "'\\\\'")] [InlineData(0.123f, "0.123f")] - [InlineData(0.123d, "0.123d")] + [InlineData(0.123d, "0.123d")] [InlineData(BindingFlags.Public, "(System.Reflection.BindingFlags)(16)")] public void ToSourceCodeSimpleTest(object original, string expected) { diff --git a/tests/BenchmarkDotNet.Tests/SummaryStyleTests.cs b/tests/BenchmarkDotNet.Tests/SummaryStyleTests.cs index 1b18b83286..9728f45a3d 100644 --- a/tests/BenchmarkDotNet.Tests/SummaryStyleTests.cs +++ b/tests/BenchmarkDotNet.Tests/SummaryStyleTests.cs @@ -21,7 +21,7 @@ public void UserCanDefineCustomSummaryStyle() ); var config = ManualConfig.CreateEmpty().With(summaryStyle); - + Assert.True(config.SummaryStyle.PrintUnitsInHeader); Assert.False(config.SummaryStyle.PrintUnitsInContent); Assert.True(config.SummaryStyle.PrintZeroValuesInContent); diff --git a/tests/BenchmarkDotNet.Tests/TypeFilterTests.cs b/tests/BenchmarkDotNet.Tests/TypeFilterTests.cs index 28c87bc937..0f341715ae 100644 --- a/tests/BenchmarkDotNet.Tests/TypeFilterTests.cs +++ b/tests/BenchmarkDotNet.Tests/TypeFilterTests.cs @@ -22,7 +22,7 @@ public class TypeFilterTests public ITestOutputHelper Output { get; } public TypeFilterTests(ITestOutputHelper output) => Output = output; - + [Fact] public void ReturnsNoBenchmarksForInvalidTypes() { @@ -83,7 +83,7 @@ public void CanSelectMethods() public void CanSelectMethodsWithFullName() { var benchmarks = Filter( - new [] { typeof(ClassA), typeof(ClassB) }, + new [] { typeof(ClassA), typeof(ClassB) }, new[] { "--filter", "BenchmarkDotNet.Tests.ClassA.Method2", "BenchmarkDotNet.Tests.ClassB.Method3" }); Assert.Equal(2, benchmarks.Count); @@ -103,7 +103,7 @@ public void CanSelectClassesUsingPatters() Assert.Contains("ClassA.Method1", benchmarks); Assert.Contains("ClassA.Method2", benchmarks); } - + [Fact] public void CanSelectClassesUsingTypeNames() { @@ -129,7 +129,7 @@ public void CanSelectClassesWithFullName() Assert.Contains("ClassA.Method1", benchmarks); Assert.Contains("ClassA.Method2", benchmarks); } - + [Fact] public void CanSelectClassesUsingPattern() { @@ -195,7 +195,7 @@ public void ClassAndMethodsCanCombined() Assert.Single(benchmarks); Assert.Contains("ClassA.Method2", benchmarks); } - + [Fact] public void GenericTypesCanBeFilteredByDisplayName() { @@ -206,15 +206,15 @@ public void GenericTypesCanBeFilteredByDisplayName() Assert.Single(benchmarks); Assert.Contains("SomeGeneric.Create", benchmarks); } - + private HashSet Filter(Type[] types, string[] args, ILogger logger = null) { var nonNullLogger = logger ?? new OutputLogger(Output); - + var config = ConfigParser.Parse(args, nonNullLogger); var runnableTypes = TypeFilter.GetTypesWithRunnableBenchmarks(types, Array.Empty(), nonNullLogger); - + return new HashSet(TypeFilter.Filter(config.config, runnableTypes.runnable) .SelectMany(runInfo => runInfo.BenchmarksCases) .Select(benchmark => $"{benchmark.Descriptor.Type.GetDisplayName()}.{benchmark.Descriptor.WorkloadMethod.Name}")); diff --git a/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs b/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs index c51fe3052d..18d947acea 100644 --- a/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs +++ b/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs @@ -16,7 +16,7 @@ public class CompilationValidatorTests public void BenchmarkedMethodNameMustNotContainWhitespaces() { Delegate method = BuildDummyMethod("Has Some Whitespaces"); - + var config = new ManualConfig().CreateImmutableConfig(); var parameters = new ValidationParameters( new[] @@ -69,10 +69,10 @@ public void BenchmarkedMethodNameMustNotUseCsharpKeywords() public void Benchmark_Class_Methods_Must_Be_Non_Static(Type type, bool hasErrors) { var validationErrors = CompilationValidator.FailOnError.Validate(BenchmarkConverter.TypeToBenchmarks(type)); - + Assert.Equal(hasErrors, validationErrors.Any()); } - + [Theory] [InlineData(typeof(PublicClass), false)] [InlineData(typeof(PublicClass.PublicNestedClass), false)] @@ -88,15 +88,15 @@ public void Benchmark_Class_Generic_Argument_Must_Be_Public(Type type, bool hasE { // Arrange var constructed = typeof(BenchmarkClass<>).MakeGenericType(type); - + // Act var validationErrors = CompilationValidator.FailOnError.Validate(BenchmarkConverter.TypeToBenchmarks(constructed)) .ToList(); - + // Assert Assert.Equal(hasErrors, validationErrors.Any()); } - + private static Delegate BuildDummyMethod(string name) { var dynamicMethod = new DynamicMethod( @@ -110,7 +110,7 @@ private static Delegate BuildDummyMethod(string name) return dynamicMethod.CreateDelegate(typeof(Func)); } - + private class PrivateNestedClass { } private protected class PrivateProtectedNestedClass { } private class PrivateClass { } @@ -120,13 +120,13 @@ protected internal class ProtectedInternalClass protected internal class ProtectedInternalNestedClass { } } } - + public class BenchmarkClassWithStaticMethod { [Benchmark] public static void StaticMethod() { } } - + public class BenchmarkClass where T : new() { [Benchmark] diff --git a/tests/BenchmarkDotNet.Tests/Validators/DeferredExecutionValidatorTests.cs b/tests/BenchmarkDotNet.Tests/Validators/DeferredExecutionValidatorTests.cs index 0d2a8d512e..c4c1765747 100644 --- a/tests/BenchmarkDotNet.Tests/Validators/DeferredExecutionValidatorTests.cs +++ b/tests/BenchmarkDotNet.Tests/Validators/DeferredExecutionValidatorTests.cs @@ -37,7 +37,7 @@ public class ReturningIEnumerableOfInt public class ReturningIQueryable { private IQueryable field = Enumerable.Empty().AsQueryable(); - + [Benchmark] public IQueryable Benchmark() => field; [Benchmark] public Task BenchmarkTask() => Task.FromResult(field); [Benchmark] public ValueTask BenchmarkValueTask() => new ValueTask(field); @@ -48,7 +48,7 @@ public class ReturningIQueryable public class ReturningIQueryableOfInt { private IQueryable field = Enumerable.Empty().AsQueryable(); - + [Benchmark] public IQueryable Benchmark() => Enumerable.Empty().AsQueryable(); [Benchmark] public Task> BenchmarkTask() => Task.FromResult(field); [Benchmark] public ValueTask> BenchmarkValueTask() => new ValueTask>(field); @@ -85,7 +85,7 @@ public void DeferredExecutionMeansError(Type returningDefferedExecutionResult) public class ReturningArray { private int[] field = Array.Empty(); - + [Benchmark] public int[] Benchmark() => field; [Benchmark] public Task BenchmarkTask() => Task.FromResult(field); [Benchmark] public ValueTask BenchmarkValueTask() => new ValueTask(field); @@ -96,7 +96,7 @@ public class ReturningArray public class ReturningDictionary { private Dictionary field = new Dictionary(); - + [Benchmark] public Dictionary Benchmark() => field; [Benchmark] public Task> BenchmarkTask() => Task.FromResult(field); [Benchmark] public ValueTask> BenchmarkValueTask() => new ValueTask>(field); diff --git a/tests/BenchmarkDotNet.Tests/XUnit/FactDotNetCore21OnlyAttribute.cs b/tests/BenchmarkDotNet.Tests/XUnit/FactDotNetCore21OnlyAttribute.cs index 357c0733e4..79b34b3ab5 100644 --- a/tests/BenchmarkDotNet.Tests/XUnit/FactDotNetCore21OnlyAttribute.cs +++ b/tests/BenchmarkDotNet.Tests/XUnit/FactDotNetCore21OnlyAttribute.cs @@ -6,9 +6,9 @@ public class FactDotNetCore21OnlyAttribute : FactAttribute { public FactDotNetCore21OnlyAttribute(string skipReason) { -#if !NETCOREAPP2_1 +#if !NETCOREAPP2_1 Skip = skipReason; -#endif +#endif } } } \ No newline at end of file diff --git a/tests/BenchmarkDotNet.Tests/XUnit/FactWindowsOnlyAttribute.cs b/tests/BenchmarkDotNet.Tests/XUnit/FactWindowsOnlyAttribute.cs index 4e777fb85e..c31e38177e 100644 --- a/tests/BenchmarkDotNet.Tests/XUnit/FactWindowsOnlyAttribute.cs +++ b/tests/BenchmarkDotNet.Tests/XUnit/FactWindowsOnlyAttribute.cs @@ -8,7 +8,7 @@ public class FactWindowsOnlyAttribute : FactAttribute // ReSharper disable once VirtualMemberCallInConstructor public FactWindowsOnlyAttribute(string nonWindowsSkipReason) { - if (!RuntimeInformation.IsWindows()) + if (!RuntimeInformation.IsWindows()) Skip = nonWindowsSkipReason; } }