Skip to content

Commit

Permalink
port to .NET Standard 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
adamsitnik committed Mar 15, 2018
1 parent 7c4b14e commit defa7ee
Show file tree
Hide file tree
Showing 27 changed files with 104 additions and 258 deletions.
17 changes: 6 additions & 11 deletions src/BenchmarkDotNet.Core/BenchmarkDotNet.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<AssemblyTitle>BenchmarkDotNet.Core</AssemblyTitle>
<TargetFrameworks>net46;netcoreapp1.1;netcoreapp2.0</TargetFrameworks>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<NoWarn>$(NoWarn);1591</NoWarn>
<AssemblyName>BenchmarkDotNet.Core</AssemblyName>
<PackageId>BenchmarkDotNet.Core</PackageId>
Expand All @@ -25,23 +25,18 @@
<ProjectReference Include="..\BenchmarkDotNet.Disassembler.x86\BenchmarkDotNet.Disassembler.x86.csproj">
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.3.0" />
<Reference Include="System.Management" />
<Reference Include="System.Xml" />
<Reference Include="System" />
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETCoreApp' ">
<PackageReference Include="System.Runtime.Serialization.Primitives" Version="4.3.0" />
<PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" />
<PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.3.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.DotNet.InternalAbstractions" Version="1.0.0" />
<PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="1.1.1" />
<PackageReference Include="Microsoft.Win32.Registry" Version="4.3.0" />
<PackageReference Include="System.Management" Version="4.5.0-preview1-26216-02" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="System.Xml.XmlSerializer" Version="4.3.0" />
<PackageReference Include="System.Diagnostics.FileVersionInfo" Version="4.3.0" />
<PackageReference Include="System.Runtime.Serialization.Primitives" Version="4.3.0" />
<PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" />
<PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.3.0" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.3.0" />
</ItemGroup>
</Project>
2 changes: 0 additions & 2 deletions src/BenchmarkDotNet.Core/Code/CodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,10 @@ private static string GetPassArguments(Benchmark benchmark)

private static string GetExtraAttributes(Target target)
{
#if !NETCOREAPP1_1
if (target.Method.GetCustomAttributes(false).OfType<System.STAThreadAttribute>().Any())
{
return "[System.STAThreadAttribute]";
}
#endif

return string.Empty;
}
Expand Down
11 changes: 5 additions & 6 deletions src/BenchmarkDotNet.Core/Diagnosers/DiagnosersLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ internal static IDiagnoser GetImplementation<TDiagnoser, TConfig>(TConfig config

private static IDiagnoser[] LoadDiagnosers()
{
#if CLASSIC
return RuntimeInformation.IsMono() ? LoadMono() : LoadClassic();
#else
if (RuntimeInformation.IsMono)
return LoadMono();
if (RuntimeInformation.IsFullFramework)
return LoadClassic();

return LoadCore();
#endif
}

private static IDiagnoser[] LoadCore() => new IDiagnoser[] { MemoryDiagnoser.Default };
Expand All @@ -49,7 +50,6 @@ private static IDiagnoser[] LoadMono()
DisassemblyDiagnoser.Create(new DisassemblyDiagnoserConfig()),
};

#if CLASSIC
private static IDiagnoser[] LoadClassic()
{
try
Expand Down Expand Up @@ -107,6 +107,5 @@ private static Assembly LoadDiagnosticsAssembly(Assembly benchmarkDotNetCoreAsse

private static IDiagnoser CreateDiagnoser(Assembly loadedAssembly, string typeName)
=> (IDiagnoser)Activator.CreateInstance(loadedAssembly.GetType(typeName));
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public IEnumerable<ValidationError> Validate(ValidationParameters validationPara
}

private bool ShouldUseMonoDisassembler(Benchmark benchmark)
=> benchmark.Job.Env.Runtime is MonoRuntime || RuntimeInformation.IsMono();
=> benchmark.Job.Env.Runtime is MonoRuntime || RuntimeInformation.IsMono;

private bool ShouldUseWindowsDissasembler(Benchmark benchmark)
=> !(benchmark.Job.Env.Runtime is MonoRuntime) && RuntimeInformation.IsWindows();
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet.Core/Diagnosers/MemoryDiagnoser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public class AllocationColumn : IColumn
public bool IsDefault(Summary summary, Benchmark benchmark) => false;

public bool IsAvailable(Summary summary)
=> !RuntimeInformation.IsMono() || results.Keys.Any(benchmark => !(benchmark.Job.Env.Runtime is MonoRuntime));
=> !RuntimeInformation.IsMono || results.Keys.Any(benchmark => !(benchmark.Job.Env.Runtime is MonoRuntime));

public bool AlwaysShow => true;
public ColumnCategory Category => ColumnCategory.Diagnoser;
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet.Core/Diagnosers/MonoDisassembler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ internal MonoDisassembler(DisassemblyDiagnoserConfig config)

internal DisassemblyResult Disassemble(Benchmark benchmark, MonoRuntime mono)
{
Debug.Assert(mono == null || !RuntimeInformation.IsMono(), "Must never be called for Non-Mono benchmarks");
Debug.Assert(mono == null || !RuntimeInformation.IsMono, "Must never be called for Non-Mono benchmarks");

var benchmarkTarget = benchmark.Target;
string fqnMethod = GetMethodName(benchmarkTarget);
Expand Down
14 changes: 5 additions & 9 deletions src/BenchmarkDotNet.Core/Diagnosers/UnresolvedDiagnoser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,14 @@
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Portability;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Validators;

namespace BenchmarkDotNet.Diagnosers
{
public class UnresolvedDiagnoser : IDiagnoser
{
private const string ErrorMessage =
#if CLASSIC
"Please make sure that you have installed the latest BenchmarkDotNet.Diagnostics.Windows package.";
#else
"To use the classic Windows diagnosers for .NET Core you need to run the benchmarks for desktop .NET. More info: http://adamsitnik.com/Hardware-Counters-Diagnoser/#how-to-get-it-running-for-net-coremono-on-windows";
#endif

private readonly Type unresolved;

public UnresolvedDiagnoser(Type unresolved) => this.unresolved = unresolved;
Expand All @@ -36,6 +29,9 @@ public void ProcessResults(DiagnoserResults results) { }
public IEnumerable<ValidationError> Validate(ValidationParameters validationParameters)
=> new[] { new ValidationError(false, GetErrorMessage()) };

private string GetErrorMessage() => $"Unable to resolve {unresolved.Name} diagnoser. {ErrorMessage}";
private string GetErrorMessage() => $@"Unable to resolve {unresolved.Name} diagnoser.
{(RuntimeInformation.IsFullFramework
? "Please make sure that you have installed the latest BenchmarkDotNet.Diagnostics.Windows package."
: "To use the classic Windows diagnosers for .NET Core you need to run the benchmarks for desktop .NET. More info: http://adamsitnik.com/Hardware-Counters-Diagnoser/#how-to-get-it-running-for-net-coremono-on-windows")}";
}
}
16 changes: 8 additions & 8 deletions src/BenchmarkDotNet.Core/Diagnosers/WindowsDisassembler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
using BenchmarkDotNet.Loggers;
using System.Linq;
using System.Text;
using BenchmarkDotNet.Engines;

namespace BenchmarkDotNet.Diagnosers
{
Expand Down Expand Up @@ -150,13 +149,14 @@ public static bool Is64Bit(Process process)
if (Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") == "x86")
return false;

#if !NETCOREAPP1_1
if (!IsWow64Process(process.Handle, out bool isWow64))
throw new Exception("Not Windows");
return !isWow64;
#else
return System.IntPtr.Size == 8; // todo: find the way to cover all scenarios for .NET Core
#endif
if (Portability.RuntimeInformation.IsWindows())
{
IsWow64Process(process.Handle, out bool isWow64);

return !isWow64;
}

return IntPtr.Size == 8; // todo: find the way to cover all scenarios for .NET Core
}

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
Expand Down
7 changes: 3 additions & 4 deletions src/BenchmarkDotNet.Core/Engines/Engine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,11 @@ private void ForceGcCollect()

private void EnableMonitoring()
{
#if CLASSIC
if (RuntimeInformation.IsMono()) // Monitoring is not available in Mono, see http://stackoverflow.com/questions/40234948/how-to-get-the-number-of-allocated-bytes-in-mono
if (RuntimeInformation.IsMono) // Monitoring is not available in Mono, see http://stackoverflow.com/questions/40234948/how-to-get-the-number-of-allocated-bytes-in-mono
return;

AppDomain.MonitoringIsEnabled = true;
#endif
if (RuntimeInformation.IsFullFramework)
AppDomain.MonitoringIsEnabled = true;
}

[UsedImplicitly]
Expand Down
13 changes: 6 additions & 7 deletions src/BenchmarkDotNet.Core/Engines/GcStats.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,20 +120,19 @@ public static GcStats FromForced(int forcedFullGarbageCollections)

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-
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
// 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();
#if NETCOREAPP1_1

if (RuntimeInformation.IsFullFramework)
return AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize;

// https://apisof.net/catalog/System.GC.GetAllocatedBytesForCurrentThread() is not part of the .NET Standard, so we use reflection to call it..
return GetAllocatedBytesForCurrentThreadDelegate.Invoke();
#elif NETCOREAPP2_0
return GC.GetAllocatedBytesForCurrentThread();
#elif CLASSIC
return AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize;
#endif
}

private static Func<long> GetAllocatedBytesForCurrentThread()
Expand Down
6 changes: 2 additions & 4 deletions src/BenchmarkDotNet.Core/Environments/HostEnvironmentInfo.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using BenchmarkDotNet.Helpers;
using BenchmarkDotNet.Horology;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Portability;
Expand Down Expand Up @@ -92,10 +91,9 @@ public override IEnumerable<string> ToFormattedString()
yield return CpuInfoFormatter.Format(CpuInfo.Value);
if (HardwareTimerKind != HardwareTimerKind.Unknown)
yield return $"Frequency={ChronometerFrequency}, Resolution={ChronometerResolution}, Timer={HardwareTimerKind.ToString().ToUpper()}";
#if !CLASSIC
if (IsDotNetCliInstalled())

if (RuntimeInformation.IsNetCore && IsDotNetCliInstalled())
yield return $".NET Core SDK={DotNetSdkVersion.Value}";
#endif
}

internal bool IsDotNetCliInstalled() => !string.IsNullOrEmpty(DotNetSdkVersion.Value);
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet.Core/Exporters/Json/SimpleJson.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@

// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html

#if NETFX_CORE || CORE
#if NETFX_CORE
#define SIMPLE_JSON_TYPEINFO
#endif

Expand Down
2 changes: 0 additions & 2 deletions src/BenchmarkDotNet.Core/Extensions/CommonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,8 @@ public static string GetColumnTitle(this IColumn column, ISummaryStyle style)

public static bool IsOneOf<T>(this T value, params T[] values) => values.Contains(value);

#if !NETCOREAPP2_0 // this method was added to the .NET Core 2.0 framework itself ;)
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
=> dictionary.TryGetValue(key, out TValue value) ? value : default;
#endif

public static double Sqr(this double x) => x * x;
public static double Pow(this double x, double k) => Math.Pow(x, k);
Expand Down
4 changes: 0 additions & 4 deletions src/BenchmarkDotNet.Core/Extensions/ProcessExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,11 @@ public static bool TrySetAffinity(

internal static void SetEnvironmentVariables(this ProcessStartInfo start, Benchmark benchmark, IResolver resolver)
{
#if !NETCOREAPP1_1 // ProcessStartInfo.EnvironmentVariables is avaialable for .NET Core 2.0+
if (!benchmark.Job.HasValue(InfrastructureMode.EnvironmentVariablesCharacteristic))
return;

foreach (var environmentVariable in benchmark.Job.Infrastructure.EnvironmentVariables)
{
start.EnvironmentVariables[environmentVariable.Key] = environmentVariable.Value;
}
#endif
}
}
}
5 changes: 1 addition & 4 deletions src/BenchmarkDotNet.Core/Extensions/ThreadExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
#if !NETCOREAPP1_1

using System;
using System;
using System.Threading;
using BenchmarkDotNet.Loggers;

Expand Down Expand Up @@ -37,4 +35,3 @@ public static bool TrySetPriority(
}
}
}
#endif
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#if CLASSIC
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Loggers;
using System;
using System.IO;
using System.Reflection;
Expand Down Expand Up @@ -61,5 +60,4 @@ private Assembly HelpTheFrameworkToResolveTheAssembly(object sender, ResolveEven
return Assembly.LoadFrom(guessedPath);
}
}
}
#endif
}
4 changes: 0 additions & 4 deletions src/BenchmarkDotNet.Core/Horology/WindowsClock.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
#if !CORE
using System.Runtime.ExceptionServices;
using System.Security;
#endif
using System.Runtime.InteropServices;

namespace BenchmarkDotNet.Horology
Expand All @@ -19,10 +17,8 @@ internal class WindowsClock : IClock
[DllImport("kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long value);

#if !CORE
[HandleProcessCorruptedStateExceptions] // #276
[SecurityCritical]
#endif
private static bool Initialize(out long qpf)
{
if (!Portability.RuntimeInformation.IsWindows())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#if !CORE
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
Expand Down Expand Up @@ -39,5 +38,4 @@ private static CpuInfo Load()
logicalCoreCount > 0 ? (int?) logicalCoreCount : null);
}
}
}
#endif
}
Loading

0 comments on commit defa7ee

Please sign in to comment.